Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Converting a set to an array for String representation

Tags:

java

arrays

set

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?

like image 446
inglesp Avatar asked Jun 14 '09 13:06

inglesp


People also ask

How do you convert a Set element to a string?

To convert a Set to a string:Pass the Set to the Array. from() method to convert it t an array. Call the join() method on the array. The join method will join the array elements into a string based on the provided separator.


2 Answers

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.

like image 83
coobird Avatar answered Oct 04 '22 16:10

coobird


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[][]).

like image 27
dfa Avatar answered Oct 04 '22 14:10

dfa