简体   繁体   中英

How to convert hash Set into array using toArray() if the method toArray is not specified?

Looking at the java api for java collections framework, I could not find toArray() method in HashSet, there is toArray() method in abstract class Set.

class Ideone {
    public static void main (String[] args) throws java.lang.Exception {
        Set x = new HashSet();
        x.add(4);
        //ArrayList<Integer> y = x.toArray(); this does not work !
        int[] y = x.toArray();//this does not work!

        System.out.println(x.toArray());//this gives some weird stuff printed : Ljava.lang.Object;@106d69c
    }
}

How do I convert hashset into array if there is no toArray() specified?

Of course HashSet implements toArray . It must implement it, since it implements the Set interface, which specifies this method. The actual implementation is in AbstractCollection which is the super class of AbstractSet which is the super class of HashSet .

First of all, you shouldn't use raw types.

Use :

Set<Integer> x = new HashSet<>();
x.add(4);

Then convert to array :

Integer[] arr = x.toArray(new Integer[x.size()]);

Using x.toArray() would give you an Object[] .

Make sure that you declare the generic for the HashSet

Set<Integer> x = new HashSet<>();

And convert it to an array like so:

int[] y = new int[x.size()];
int c = 0;
for(int x : x) y[c++] = x;

First Line

ArrayList y = x.toArray(); this does not work !

First of all you used Set x = new HashSet(); ie raw type . Compiler does not know that s it going to contain integer object but with above line on left hand side you are saying its going to be arraylist of integer where actually its an array

Second line

int[] y = x.toArray();//this does not work!

with above line on left hand side you are saying its going to be array of integer where actually its an array of objects

This will work

Object[] y = x.toArray();

But this is not the right way . You should not use raw types

 Set<Integer> x = new HashSet<>();
 Integer[] intArray= x.toArray(new Integer[x.size()]);

System.out.println(x.toArray());//this gives some weird stuff printed : Ljava.lang.Object;@106d69c

Its printing toString representation of array object . Thats why you are seeing it as Ljava.lang.Object;@106d69c

If you want to print each element , iterate over it and then print it.

It looks like you originally wanted to create an ArrayList rather than a simple Array. So, try this!

class Ideone 
{
        public static void main (String[] args) throws java.lang.Exception   
        {
            Set x = new HashSet();
            x.add(4);
            ArrayList<Integer> y = new ArrayList<>(x);
            System.out.println(y);
        }
}

Comparison in JDK 7 sorting a small map, using TreeSet , ArrayList and Array :

long start  = System.currentTimeMillis(); 
for(int i=0; i<10000000; i++){ 
   TreeSet a   = new TreeSet(payloads.keySet());                           
} 
System.out.println("TreeSet: "    + (System.currentTimeMillis()-start) + " ms.");
start       = System.currentTimeMillis(); 
for(int i=0; i<10000000; i++){ 
   ArrayList a = new ArrayList(payloads.keySet()); 
   Collections.sort(a);    
} 
System.out.println("ArrayList: "  + (System.currentTimeMillis()-start) + " ms.");
start       = System.currentTimeMillis(); 
for(int i=0; i<10000000; i++){ 
   String[] a = payloads.keySet().toArray(new String[payloads.size()]); 
   Arrays.sort(a);    
} 
System.out.println("Array: "  + (System.currentTimeMillis()-start) + " ms.");

Yields:

TreeSet: 1527 ms.
ArrayList: 943 ms.
Array: 485 ms.

We can iterate through the loop and store the values into the array.

int[] answer = new int[set1.size()];
int i = 0;
for (int num : set1) {
      answer[i++] = num;
}

you can convert a hashset to arraylist then to arrays int[]. this approach is good if u want to dynamically convert it back to array.

this would be a one-liner solution.

Set<Integer> my_set = new HashSet<>();
my_set.add(4);

int[] result = new ArrayList<>(my_set).stream().mapToInt(i -> i).toArray();
System.out.println(Arrays.toString(result)); // [4]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM