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?
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.
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.
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[][]).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With