2013-05-19 11 views
5

ho una mappacome convertire hashmap a matrice di voci

private HashMap<Character, Integer> map;

voglio convertirlo in serie, ma quando lo faccio/ottengo questo:

Entry<Character, Integer> t = map.entrySet().toArray();  
**Type mismatch: cannot convert from Object[] to Map.Entry<Character,Integer>** 

Entry<Character, Integer>[] t = null; 
map.entrySet().toArray(t); 
**Exception in thread "main" java.lang.NullPointerException** 

Entry<Character, Integer>[] t = new Entry<Character, Integer>[1]; 
map.entrySet().toArray(t); 
    **Cannot create a generic array of Map.Entry<Character,Integer>** 

Entry<Character, Integer>[] t = null; 
t = map.entrySet().toArray(t); 
**Exception in thread "main" java.lang.NullPointerException** 

Così come convertire HashMap a Array? Nessuna delle risposte trovate in altri argomenti di lavoro.

+1

http://stackoverflow.com/questions/529085/java-how-to-generic-array-creation Il fatto è che è n o possibile creare un array generico come 'Entry []'. Usa invece un 'Elenco >'. – Natix

risposta

11

penso che questo funzionerà:

Entry<Character, Integer>[] t = (Entry<Character, Integer>[]) 
     (map.entrySet().toArray(new Map.Entry[map.size()]));  

... ma è necessario un'annotazione @SuppressWarning per eliminare l'avviso circa la typecast pericoloso.

+0

Sì, è stato fantastico! Vera magia – Yoda

1

Non sono sicuro del modo in cui hai provato. Quello che vorrei fare è

Quando fate che si otterrà un entrySet, in modo che i dati saranno memorizzati come voce

Quindi, se si desidera mantenere nel entrySet si può fare questo:

List<Entry<Character, Integer>> list = new ArrayList<Entry<Character, Integer>>(); 

for(Entry<Character, Integer> entry : map.entrySet()) { 
    list.add(entry); 
} 

Si noti inoltre che si otterrà sempre un ordine diverso quando si esegue questa operazione, poiché HashMap non è ordinato.

Oppure si può fare una classe per contenere i dati Entry:

public class Data { 
    public Character character; 
    public Integer value; 

    public Data(Character char, Integer value) { 
     this.character = character; 
     this.value = value; 
    } 
} 

ed estrarlo con:

List<Data> list = new ArrayList<Data>(); 

for(Entry<Character, Integer> entry : map.entrySet()) { 
    list.add(new Data(entry.getKey(), entry.getValue())); 
} 
0

Un'altra variante che sembra un po 'più pulito (ma ancora richiede l'@SuppressWarnings):

@SuppressWarnings("unchecked") 
Entry<Character, Integer>[] t = map.entrySet().toArray(new Entry[map.size()]);