简体   繁体   中英

Can I use String[] as HashMap values in Java?

I am a beginner in Java programming. I want to create a HashMap whose values are String[]'s.

Suppose I have a JTable parametersTable with values in columns 2, 3, and 4 that I wish to fetch from each row. Each three-value set constitutes a HashMap value ( String[] ).

HashMap<String, String[]> map = new HashMap<String, String[]>();
String[] row = {"one", "two", "three", "four", "five", "six", "seven","eight","nine","ten","eleven"};
for (int i=0; i<row.length; i++) {
map.put(row[i], new String[] {
   (String) parametersTable.getValueAt(i, 2),
   (String) parametersTable.getValueAt(i, 3),
   (String) parametersTable.getValueAt(i, 4)});
}
System.out.println(map);

The above code outputs:

{nine=[Ljava.lang.String;@187930f1, six=[Ljava.lang.String;@2a8000ab, four=[Ljava.lang.String;@4436b0fd, one=[Ljava.lang.String;@134bc965, seven=[Ljava.lang.String;@42e49d45, eleven=[Ljava.lang.String;@68cb58ea, ten=[Ljava.lang.String;@198bbc56, two=[Ljava.lang.String;@54464ee3, three=[Ljava.lang.String;@32aeff9b, five=[Ljava.lang.String;@90ed2c, eight=[Ljava.lang.String;@443d9864}

Why is the output something cryptic and not the values like I expect?

Why is the output something cryptic and not the values like I expect?

[Ljava.lang.String;@ is the default representation of String arrays toString() method.

Use Arrays.toString method instead.

So instead of System.out.println(map) use this to get a meaningful representation

 for(Map.Entry<String, String[]> entry : map.entrySet()) {
       System.out.println(entry.getKey() + " -> " + Arrays.toString(entry.getValue()));
 }

Try this method :)

     static void print(HashMap<String, String[]> map) {

        StringBuilder builder = new StringBuilder();
        for(Map.Entry<String, String[]> e : map.entrySet()) {

            builder.append(e.getKey()).append(" -> [");
            boolean tmp = false;
            for(String s : e.getValue()) {
                if(tmp) {
                    builder.append(" ");
                }
                tmp = true;
                builder.append(s);

            }
            builder.append("]\n");

        }
        System.out.println(builder.toString());

    }

You got [Ljava.lang.String;@90ed2c because default method toString() for array was invoked.

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