-2

I'm trying print out a a simple hash map with a string key and char array except I'm not getting the proper output.

Output basically goes:

 Key :3  Value :[C@35960f05
 Key :2  Value :[C@35960f05
 Key :1  Value :[C@35960f05

Which I guess is the code the char arrays actual location? I didn't google because I'm honestly not sure what this means or what it's called. Could please someone tell me how to fix this or where I might find information so I can find my own solution. Here is my code:

public class MapExample {

public static void main(String[] args) {

    Map<String, char[]> mp = new HashMap<String, char[]>();

    char[] words = new char[3];
    words[0] = 'a';
    words[1] = 'b';
    words[2] = 'c';

    mp.put("1", words);
    mp.put("2", words);
    mp.put("3", words);

    Set s = mp.entrySet();
    Iterator it = s.iterator();

    while (it.hasNext()) {
        Map.Entry m = (Map.Entry) it.next();
        String key = (String) m.getKey();
        char[] value = (char[]) m.getValue();

        System.out.println("Key :" + key + "  Value :" + value);
    }
}
}
giannis christofakis
  • 8,201
  • 4
  • 54
  • 65
David
  • 501
  • 3
  • 10
  • 30

3 Answers3

1

Arrays while be reference types, do not inherit from the base Object superclass in Java, therefore they cannot and don't override the toString() method to provide a textual representation for themselves.

You can easily write a function that returns an Array as a String or you could use the java.util.Arrays class toString() method.

 import java.util.Arrays;
 System.out.println("Key :" + key + "  Value :" + Arrays.toString(value));

It might be better practice to write your own method however, I'll give you a head start with the signature:

private String charArrayToString(char[] chars) {
    return null;
}
Hunter McMillen
  • 59,865
  • 24
  • 119
  • 170
0

Because your value is array of chars (char[]). So when you call

System.out.println(... + value);

you call toString() method of an array. It prints something like object descriptor. The only solution is to get the value array, iterate over it and create a string out of it. Or call Arrays.toString(value).

darijan
  • 9,725
  • 25
  • 38
0

Arrays in java don't override the toString() from Object, so you just get an @ followed by their hashcode in Hex.

The class Arrays provides several convenience methods for doing things like this; Arrays.toString() being the proper method to print an array, and if you're working with multi-dimensional arrays you can use Arrays.deepToString().

http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html

Robert Mitchell
  • 892
  • 7
  • 9