This discussion is archived
4 Replies Latest reply: Jul 15, 2012 3:21 AM by Jörg RSS

Retrieving the ints from a set

Jörg Explorer
Currently Being Moderated
Hello,

is there no way to put all the ints of a set into an int array than via an iterator?
import java.util.*;

public class T {

  public static void main(String args[]) {
    HashSet<Integer> mySet= new HashSet<>();
    mySet.add(3);
    mySet.add(4);
//    int[] iArray= new int[mySet.size()];
//    iArray= mySet.toArray(iArray); //no suitable method found for toArray(int[])
    Integer[] iArray= new Integer[mySet.size()];
    iArray= mySet.toArray(iArray);
    int jArray[]= new int[mySet.size()];
//    jArray= (int[])mySet.toArray(jArray); // inconvertible types
    System.arraycopy(iArray, 0, jArray, 0, iArray.length); // ArrayStoreException
  }

}
  • 1. Re: Retrieving the ints from a set
    BIJ001 Explorer
    Currently Being Moderated
    import java.util.*;
     
    public class T {
     
      public static void main(String args[]) {
        HashSet<Integer> mySet= new HashSet<Integer>();
        mySet.add(3);
        mySet.add(4);
    //    int[] iArray= new int[mySet.size()];
    //    iArray= mySet.toArray(iArray); //no suitable method found for toArray(int[])
        Integer[] iArray= new Integer[mySet.size()];
        iArray= mySet.toArray(iArray);
        int jArray[]= new int[mySet.size()];
    //    jArray= (int[])mySet.toArray(jArray); // inconvertible types
    //    System.arraycopy(iArray, 0, jArray, 0, iArray.length); // ArrayStoreException
         int ct=0;
         for(Integer ii : iArray) jArray [ct++]=ii;
      }
     
    }
  • 2. Re: Retrieving the ints from a set
    EJP Guru
    Currently Being Moderated
    What's the objection to using an Iterator?
  • 3. Re: Retrieving the ints from a set
    Jörg Explorer
    Currently Being Moderated
    Thank you both for your responses. My question was not correct. It should have read "Why is autoboxing not working with Set.toArray(T[] a)?" The code shows that autoboxing is working when filling the set. So I was wondering that vice versa it was not possible.
  • 4. Re: Retrieving the ints from a set
    EJP Guru
    Currently Being Moderated
    Because the type of the collection is <Integer> and the type of the array is int[] and there is no autoboxing of array types.

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points