2010-12-28 17 views
26

Desidero creare un array che contenga ArrayList < Stringa> elementi.Creazione di un array di elementi ArrayList <String>

Ho provato

ArrayList<String> name[] = new ArrayList<String>()[]; 

ma questo non sembra funzionare.

+0

You want an arraylis t di arraylists. Perché dovresti usare un array in un senso e un arraylist in altri? – Falmarri

+2

So quanti elementi ci saranno. È ancora meglio usare un arraylist di arraylists? – sighol

+0

Questo è un duplicato di: http://stackoverflow.com/questions/2792731/how-to-an-ar-array-of-hashmaps/2792743#2792743 – Tom

risposta

33

Non è possibile creare un array di un tipo generico.

Invece, è possibile creare un ArrayList<ArrayList<String>>.

+0

Ciao, in tal caso, com'era possibile qui? https://stackoverflow.com/questions/22747528/how-to-create-an-array-of-arraylists-in-java – Harsha

11

Il modo corretto è:

ArrayList<String> name[] = new ArrayList[9]; 

Tuttavia, questo non funzionerà neanche, dal momento che non è possibile fare un array con un tipo generico, ciò che si sta cercando di fare è una matrice, e questo dovrebbe essere fatto in questo modo:

String name[][]; 
+3

ma il primo funziona, tuttavia mostra un avviso di sicurezza del tipo. –

2
ArrayList<ArrayList<String>> name= new ArrayList<ArrayList<String>>(/*capacity*/); 
2

Se si desidera una serie di ArrayList, dovrete inizializzare ogni posizione dell'array individualmente:

int size = 9; // 9 is just an example 
// you can remove the annotation, but you'll be warned: 
// Type safety: The expression of type ArrayList[] needs unchecked conversion 
// to conform to ArrayList<String>[] 
@SuppressWarnings("unchecked") 
ArrayList<String> name[] = new ArrayList[ size]; 
for(int i = 0; i < size; i++) { 
    name[ i] = new ArrayList<String>(); 
} 
5

Questo non è corretto OO e questo tipo di codice è molto implementato accoppiato. Se hai bisogno di fare una cosa del genere, probabilmente hai fatto qualcosa di sbagliato. Se il codice non è tuo, la persona che lo ha fatto probabilmente ha fatto qualcosa di sbagliato.

Se sai quanti elementi ci sono (o anche se non lo hai fatto), perché non usare Map<Integer,List<String>>?

+1

Usare Map è una buona idea! Mi ha aiutato, grazie! – Progtopus

9

So che questo è un po 'vecchio ma ho intenzione di rispondere a questo comunque per le viste future.

Se si vuole veramente un ArrayList<String>[] struttura, si può semplicemente creare una classe che estende ArrayList e fare una serie di quella classe:

public class StringArrayList extends ArrayList<String>{} 

E nell'implementazione:

ArrayList<String> name[] = new StringArrayList[9]; 

Ecco un esempio:

package testspace.arrays; 

import java.util.List; 

public class TestStringArray { 

    public static void main(String[] args) { 
     List<String>[] arr = new StringArrayList[10]; 
     for(int i = 0; i < arr.length; i++){ 
      // CANNOT use generic 'new ArrayList<String>()' 
      arr[i] = new StringArrayList(); 
      for(int j = 0; j < arr.length; j++){ 
       arr[i].add("list item #(" + j + "|" + i + ")"); 
      } 
     } 

     StringBuilder sb = new StringBuilder(); 
     for(final List<String> list : arr){ 
      for(final String str : list){ 
       sb.append(str + " "); 
      } 
      sb.append("\n"); 
     } 
     System.out.println(sb.toString()); 
    } 

} 

NOTA Si otterrà un errore di runtime se si utilizza questo, invece: arr[i] = new ArrayList<String>()

0

Ho provato questo senza un errore, anche se ho putted un limite nella matrice meno rispetto alla quantità di elementi aggiunti:

package Testes.src; 

import java.util.ArrayList; 
import java.util.List; 

public class Testes { 

    private List<String> name=new ArrayList<String>(1); 

    public Testes(){ 
     for (int i = 1; i <= 100; i++) { 
      name.add("Teste"+Integer.toString(i)); 
     } 
     for (int i = 0; i < name.size(); i++) { 
      System.out.println(name.get(i)); 
     } 
    } 
    public static void main(String [] args) 
    { 
     Testes t1=new Testes(); 
    } 
} 
0

So che questo è un vecchio post, ma qualcuno ha appena fatto la stessa domanda e poiché nessuno ha menzionato la seguente soluzione, eccola qui.

Un modo per aggirarlo potrebbe essere qualcosa come un array 2d (la domanda recente riguardava un array 2d o ArrayList) di oggetti e quindi dovresti essere in grado di inserire i riferimenti di ArrayList nell'array. Non l'ho provato, ma qualcosa del genere dovrebbe funzionare.

Object [][] data = new Object[5][5]; 
data[0][0] = new ArrayList<String>(); // etc . . . 
0

Si può provare questo:

ArrayList[] arr=new ArrayList[5]; 
for(int i=0;i<5;i++) 
    arr[i]=new ArrayList<String>(); 
arr[1].add("35"); 
arr[1].add("ME"); 
arr[1].add("HELLO"); 
System.out.println(arr[1]); 

uscita:

[35, ME, HELLO] 
0
// This is the not correct way 
ArrayList<String> name[] = new ArrayList<String>()[]; 

// This is the correct way 
ArrayList<String> list[] = new ArrayList[2]; 

list[0] = new ArrayList(); 
list[1] = new ArrayList(); 

list[0].add("Some String 11"); 
list[0].add("Some String 22"); 

list[1].add("Some String 1111"); 
list[1].add("Some String 2222"); 
+2

La risposta è stata 7 anni fa. Quale nuovo valore porta la tua risposta? –

0

Array di ArrayLists, ad esempio con i cicli

//Declare 
Object[] arrayLists = new Object[size];  

//Fill 
for (int j=0; j < size; j++) { 
    arrayLists[k]= generateAnArrayList(j); //or whatnot 
} 

//Usage 
for (int j=0; j < size; j++) { 
    ArrayList<Long> al = (ArrayList<Long>) arrayLists[j]; 
    //do something here 
} 
Problemi correlati