Reputation: 5068
It compiles and runs without problems, but I cannot understand why second statement return false:
String s0 ="0123";
String s1 ="0123";
System.out.println(new HashSet<>(Arrays.asList(ArrayUtils.toObject(s1.toCharArray()))).containsAll(Arrays.asList(ArrayUtils.toObject(s0.toCharArray()))));
System.out.println(new HashSet<>(Arrays.asList(s1.toCharArray())).containsAll(Arrays.asList(s0.toCharArray())));
Output:
true
false
JDK 1.8
EDIT:
Thank you @Eran There is a compilation problem when I avoid diamond operator like this:
new HashSet<Character>(Arrays.asList(s1.toCharArray())).containsAll(Arrays.asList(s0.toCharArray()));
Upvotes: 1
Views: 137
Reputation: 394156
Since s0.toCharArray()
is a primitive array (char[]
), Arrays.asList(s0.toCharArray())
is a List whose single element is a char[]
.
Similarly, new HashSet<>(Arrays.asList(s1.toCharArray()))
is a Set that contains a single char[]
.
Those two char[]
objects are not equal, since arrays don't override Object
's equals
and each call to toCharArray[]
creates a new array isntance, so even if s0==s1
, s0.toCharArray() != s1.toCharArray()
and s0.toCharArray().equals(s1.toCharArray())
is false.
In your first line of code, I'm assuming that ArrayUtils.toObject
converts the primitive array to a reference array (i.e. from char[]
to Character[]
), which is why containsAll
returns true (since both the HashSet
and the List
contain 4 Character
instances, and the Character
class overrides equals
, so all the Character
s in the List
are contained in the HashSet
).
Upvotes: 3