简体   繁体   中英

Integer Object type conversion

I have a code which is not working as I want it to work.. I am converting HashMap to Integer Array.. But it displays an error: Object[] Integer[] type mismatch.. Here's the code:

HashMap<String,Integer> hm = new HashMap<String,Integer>(); 
hm.put((s.charAt(i) + "") , (hm.get(s.charAt(i)+""))+1); // i is for loop
ArrayList<Integer> alist = new ArrayList<Integer>(hm.values());
Integer[] i = alist.toArray(); // error at this line

I have to use for loop to create an integer array from ArrayList..

for(int k=0;k<alist.length;k++)
{
 i[k] = (Integer) alist[k];
}

I checked it against alist.get(o) instanceof Integer which returns true indicating that it is an Integer Object.. But it still displays an error at line 4 of the code..

Thanks in advance.

List.toArray() is overloaded :

Which one you used :

Object[] toArray();

and :

T[] toArray(T[] a);

Use the last one as you want to convert the List to an array of the generic type of the List and not an array of Object .

Integer[] i = alist.toArray(new Integer[alist.size()]); 

As a side note, you could improve the code by programming by interface, using the diamond operator and sparing not required objects.
Note that toArray() comes from the Collection interface and AbstractCollection that is the base class of most of concrete Collection subclasses defines an implementation for toArray() .

So you could write :

Map<String,Integer> hm = new HashMap<>();  
hm.put((s.charAt(i) + "") , (hm.get(s.charAt(i)+""))+1); // i is for loop
Integer[] i = hm.values().toArray(new Integer[hm.values().size()]);

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