1. Error
Today, when testing the code to find the program error, see the code to know is to use the Hashmap.values () method when the error. Because a collection of map values needs to be fetched in the project and then traversed, it is natural to call the Hashmap.values () method, as shown below
Package Collections;import Java.util.hashmap;import Java.util.list;import java.util.map;public class Test {/** * @param args */public static void main (string[] args) {map<string,string> Map = new hashmap<string,string> (); map.put ("A", "a"), Map.put ("B", "B"), Map.put ("C", "C"), Map.put ("D", "D"), Map.put ("E", "E"); List<string> valueslist = (list<string>) map.values (); for (String str:valueslist) {System.out.println (str );}}}
Run time throws an exception, the exception information is as follows:
Exception in thread "main" Java.lang.classcastexception:java.util.hashmap$values cannot is cast to Java.util.Listat Coll Ections. Test.main (TEST.JAVA:20)
2. Error cause Analysis
First found the values () method where the source code, the information is as follows:
Public collection<v> values () { collection<v> vs = values; return (vs! = null? VS: (values = new values ())); }
The original values () method simply returned a collection collection, but as the usage in the program shows, a type conversion error occurs when the transition is down. So how do we get the structure we want?
3. Workaround
In ArrayList, there is a constructor
Public ArrayList (collection<? extends e> c) { elementdata = C.toarray (); size = Elementdata.length; C.toarray might (incorrectly) not return object[] (see 6260652) if (Elementdata.getclass ()! = Object[].class) Elementdata = arrays.copyof (elementdata, size, object[].class); }
You can accept a parameter of a collection type and then return a list, which achieves the intended purpose. The code is as follows
Package Collections;import Java.util.arraylist;import java.util.hashmap;import java.util.list;import java.util.Map; public class Test {/** * @param args */public static void main (string[] args) {map<string,string> Map = new HashMap <String,String> (); Map.put ("A", "a"), Map.put ("B", "B"), Map.put ("C", "C"), Map.put ("D", "D"), Map.put ("E", "E"); /list<string> valueslist = (list<string>) map.values (); list<string> valueslist = new arraylist<string> (Map.values ()); for (String str:valueslist) { System.out.println (str);}}}
Misuse of the Java hashmap.values () method