12

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

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]]

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);
    }
}

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

Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
Rushy Panchal
  • 16,979
  • 16
  • 61
  • 94

3 Answers3

43

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):

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

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();
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
  • saved my life , I would recommend just `for(Integer element : keys) array[index++] = element.intValue();` to be replaced with `for(Integer element : keys) array[index++] = element` to remove boxing – Stavro Xhardha Dec 11 '18 at 13:27
3

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

dan04
  • 87,747
  • 23
  • 163
  • 198
2

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

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

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.

Ray Stojonic
  • 1,260
  • 1
  • 7
  • 11