web-dev-qa-db-fra.com

Comment convertir un hachage Définissez dans un tableau en utilisant toArray () si la méthode toArray n'est pas spécifiée?

En regardant le framework Java api pour les collections Java, je n'ai pas trouvé de méthode toArray () dans HashSet, il existe une méthode toArray () dans la classe abstraite 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
    }
}

Comment convertir un hashset en tableau s'il n'y a pas de toArray () spécifié?

12
ERJAN

Bien sûr, HashSet implémente toArray. Il doit l'implémenter, puisqu'il implémente l'interface Set, qui spécifie cette méthode. L'implémentation réelle est dans AbstractCollection qui est la super classe de AbstractSet qui est la super classe de HashSet.

Tout d'abord, vous ne devriez pas utiliser de types bruts.

Utilisation :

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

Puis convertissez en tableau:

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

Utiliser x.toArray() vous donnerait un Object[].

28
Eran

Assurez-vous de déclarer le générique pour la HashSet

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

Et convertissez-le en un tableau comme celui-ci:

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

Il semble que vous vouliez initialement créer un ArrayList plutôt qu'un simple Array. Alors, essayez ceci!

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

Comparaison dans JDK 7 triant une petite carte en utilisant TreeSet, ArrayList et 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.");

Rendements:

TreeSet: 1527 ms.
Liste de tableaux: 943 ms.
Matrice: 485 ms.

0
sjzack