【问题标题】:Get array of Map's keys [duplicate]获取地图键的数组[重复]
【发布时间】:2013-04-18 16:56:36
【问题描述】:

我正在尝试以 Python 为基础学习 Java,所以请多多包涵。

我正在实现一种埃拉托色尼筛法(我在 Python 中有一个;试图将其转换为 Java):

def prevPrimes(n):
    """Generates a list of primes up to 'n'"""
    primes_dict = {i : True for i in range(3, n + 1, 2)}
    for i in primes_dict:
        if primes_dict[i]:
            num = i
        while (num * i <= n):
            primes_dict[num*i] = False
            num += 2
    primes_dict[2] = True
    return [num for num in primes_dict if primes_dict[num]]

这是我将其转换为 Java 的尝试:

import java.util.*;
public class Sieve {
    public static void sieve(int n){
        System.out.println(n);
        Map primes = new HashMap();
        for(int x = 0; x < n+1; x++){
            primes.put(x, true);
        }
        Set primeKeys = primes.keySet();
        int[] keys = toArray(primeKeys);  // attempt to convert the set to an array
        System.out.println(primesKeys); // the conversion does not work
        for(int x: keys){
            System.out.println(x);
        }
        // still have more to add
        System.out.println(primes);
    }
}

我得到的错误是它找不到方法toArray(java.util.Set)。我该如何解决这个问题?

【问题讨论】:

    标签: java python arrays dictionary


    【解决方案1】:

    首先,使用泛型:

    Map<Integer, Boolean> map = new HashMap<Integer, Boolean>();
    Set<Integer> keys = map.keySet();
    

    其次,要将集合转换为数组,可以使用toArray(T[] a)

    Integer[] array = keys.toArray(new Integer[keys.size()]);
    

    如果你想要int 而不是Integer,那么遍历每个元素:

    int[] array = new int[keys.size()];
    int index = 0;
    for(Integer element : keys) array[index++] = element.intValue();
    

    【讨论】:

    • 救了我的命,我建议将 for(Integer element : keys) array[index++] = element.intValue(); 替换为 for(Integer element : keys) array[index++] = element 以删除拳击
    【解决方案2】:

    使用primeKeys.toArray() 代替toArray(primeKeys)

    【讨论】:

    • int[] keys = primeKeys.toArray() 突出显示括号,我收到此错误:incompatible types
    【解决方案3】:

    toArray()Collection 类的成员,所以只需输入Collection.toArray(...) 并导入java.util.Collection;

    注意:toArray() 返回一个 Object[],因此您必须将其转换为 Integer[] 并将其分配给 Integer[] 引用:

    Integer[] array = (Integer[])Collection.toArray( someCollection );
    

    由于自动装箱,整数现在大部分时间都像整数一样工作。

    编辑:dan04 的解决方案非常酷,希望我能想到这一点……无论如何,您仍然需要强制转换并分配给 Object[] 类型。

    【讨论】:

      猜你喜欢
      • 2013-05-20
      • 1970-01-01
      • 1970-01-01
      • 2017-06-05
      • 2011-09-21
      • 2016-12-02
      • 1970-01-01
      • 2020-01-06
      • 2016-05-30
      相关资源
      最近更新 更多