简体   繁体   中英

how to get the values from hash map and put them in array?

I am trying to pull the values from hash map and put them in array, but I keep getting a null pointer exception.

Is there any other way to do this?

//some code....
String n[]=new String[tcur.getCount()];;
String t[]=new String[tcur.getCount()];;
HashMap<Integer, String> typehashmap=new HashMap<Integer, String>();
HashMap<Integer, String> namehashmap=new HashMap<Integer, String>();

//some code..
String   type[]=typehashmap.keySet().toArray(new String[typehashmap.size()]);
String   name[]=namehashmap.keySet().toArray(new String[namehashmap.size()]);          


for (int i=0;i<=type.length;i++) {
    n[i]=namehashmap.get(nameiterator[i]).toString();
    System.out.println(n[i]);
    t[i]=typehashmap.get(typeiterator[i]).toString();
    System.out.println (t[i]);
}

Why don't you use this?

 Set<Integer> keys = namehashmap.keySet();
 Collection<String> values = namehashmap.values();

You can work with values collection many ways.

 for(String value:values) { ... }

If you still want arrays, maybe you want do:

 keys.toArray();
 values.toArray();

Real question is, what do you try to accomplish? Are your two HashMaps interconnected, say entries with the same integer key in both maps belong together? If so, I would first consider making a wrapper class for this eg:

private static class TypeName {
   private String type;
   private String name;
}

And using a HashMap

Furthermore, IMHO the best way to iterate over a HashMap is to use the entry set:

Map<A,B> map = new HashMap<A,B>();
for(Entry<A,B> entry : map.entrySet()) {
   A a = entry.getKey();
   B b = entry.getValue();
   // do things
}

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