获取Map的键数组

Rus*_*hal 4 python java arrays dictionary

我正在尝试以Python为基础学习Java,所以请耐心等待.

我正在实现一个Sierat of Eratosthenes方法(我在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]]
Run Code Online (Sandbox Code Playgroud)

这是我尝试将其转换为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);
    }
}
Run Code Online (Sandbox Code Playgroud)

我得到的错误是它找不到方法toArray(java.util.Set).我怎样才能解决这个问题?

Eng*_*uad 33

首先,使用泛型:

Map<Integer, Boolean> map = new HashMap<Integer, Boolean>();
Set<Integer> keys = map.keySet();
Run Code Online (Sandbox Code Playgroud)

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

Integer[] array = keys.toArray(new Integer[keys.size()]);
Run Code Online (Sandbox Code Playgroud)

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

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