Java: Converting a set to an array for String repr

2019-03-14 07:19发布

From Sun's Java Tutorial, I would have thought this code would convert a set into an array.

import java.util.*;

public class Blagh {
    public static void main(String[] args) {
        Set<String> set = new HashSet<String>();
        set.add("a");
        set.add("b");
        set.add("c");
        String[] array = set.toArray(new String[0]);
        System.out.println(set);
        System.out.println(array);
    }
}

However, this gives

[a, c, b]
[Ljava.lang.String;@9b49e6

What have I misunderstood?

标签: java arrays set
6条回答
forever°为你锁心
2楼-- · 2019-03-14 07:31

I don't think you have misunderstood anything; the code should work. The array, however, is not smart enough to print its contents in the toString method, so you'll have to print the contents with

for(String s : array) println(s);

or something like that.

查看更多
不美不萌又怎样
3楼-- · 2019-03-14 07:33

The code works fine.

Replace:

System.out.println(array);

With:

System.out.println(Arrays.toString(array));

Output:

[b, c, a]
[b, c, a]

The String representation of an array displays the a "textual representation" of the array, obtained by Object.toString -- which is the class name and the hash code of the array as a hexidecimal string.

查看更多
我想做一个坏孩纸
4楼-- · 2019-03-14 07:34

You have the correct result. Unfortunately the toString()-method on the array is still the original Object.toString() so the output is somewhat unusable per default but that goes for all arrays.

查看更多
够拽才男人
5楼-- · 2019-03-14 07:42

As dfa mentioned, you can just replace:

System.out.println(array);

with...

System.out.println(Arrays.toString(array));
查看更多
聊天终结者
6楼-- · 2019-03-14 07:44

It's OK.

You are not seeing the array contents with System.out.println(array) because println calls object.toString() to get the bytes from an Object for output.

Since HashSet overrides the default toString() implementation, you can see the set contents with System.out.println(set);

As arrays do not override the default toString() (that gives the class name and some sort of identity hash code), you are getting the fuzzy [Ljava.lang.String;@9b49e6

Hope that helps

查看更多
Luminary・发光体
7楼-- · 2019-03-14 07:48

for the sake of completeness check also java.util.Arrays.toString and java.util.Arrays.deepToString.

The latter is particularly useful when dealing with nested arrays (like Object[][]).

查看更多
登录 后发表回答