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?
HashMap stores key, value pairs and it does not allow duplicate keys. If the key is duplicate then the old key is replaced with the new value.
A LinkedHashMap cannot contain duplicate keys. LinkedHashMap can have null values and the null key. Unlike HashMap, the iteration order of the elements in a LinkedHashMap is predictable.
A TreeMap cannot contain duplicate keys. TreeMap cannot contain the null key. However, It can have null values.
In HashSet, we store objects. It does not allow duplicate keys, but duplicate values are allowed. It does not allow duplicate values. It can contain a single null key and multiple null values.
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();
Use primeKeys.toArray()
instead of toArray(primeKeys)
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With