获取Map' s键的数组 [英] Get array of Map's keys

查看:78
本文介绍了获取Map' s键的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Python学习Java,所以请多多包涵。

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

我正在实现一种Eratosthenes筛方法(我在Python中有一个;尝试将其转换为Java):

I am implementing a Sieve of Eratosthenes method (I have one in Python; trying to convert it to 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:

This is my attempt to convert it to 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)。我该如何解决?

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

推荐答案

首先,使用泛型:

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

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

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

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

,如果要 int 而不是 Integer ,然后遍历每个元素:

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

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

这篇关于获取Map&#39; s键的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆