Java 获取 Map 键的数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16203880/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 05:46:22  来源:igfitidea点击:

Get array of Map's keys

javapythonarraysdictionary

提问by Rushy Panchal

I am trying to learn Java with a Python basis, so please bear with me.

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

I am implementing a Sieve of Eratosthenes method (I have one in Python; trying to convert it to Java):

我正在实施一种 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]]

This is my attempt to convert it to Java:

这是我将其转换为 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);
    }
}

The error I get is that it cannot find the method toArray(java.util.Set). How can I fix this?

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

采纳答案by Eng.Fouad

First of all, use generics:

首先,使用泛型:

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

Second, to convert the set to an array, you can use toArray(T[] a):

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

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

and if you want intinstead of Integer, then iterate over each element:

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

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

回答by dan04

Use primeKeys.toArray()instead of toArray(primeKeys).

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

回答by Ray Stojonic

toArray()is a member of the Collectionclass, so just put Collection.toArray(...)and import java.util.Collection;

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

Note: toArray()returns an Object[], so you'll have to cast it to Integer[] and assign it to an Integer[] reference:

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

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

Thanks to autoboxing, Integers now work like ints, most of the time.

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

edit: dan04's solution is pretty cool, wish I'd thought of that...anyway, you'll still have to cast and assign to a Object[] type.

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