0

I have an ArrayList:

List<MyClass> xxx = new ArrayList<MyClass>(functionThatGetsAList());

When I test xxx.size() I get 3, which is right. Then I try to cast:

Set<MyClass> yyy = new HashSet<MyClass>(xxx);

or alternatively:

Set<MyClass> yyy = new HashSet<MyClass>();
yyy.addAll(xxx);

In both cases yyy.size() is 1 and it only copies the first object. Why?

Duncan Jones
  • 67,400
  • 29
  • 193
  • 254
user3170595
  • 109
  • 1
  • 1
  • 12

2 Answers2

1

From the documentation for HashSet

boolean add(E e) Adds the specified element to this set if it is not already present.

Try adding those elements from the list to the set in a loop.

does set.add(l); return true for every iteration? If not I think its safe to assume that the things that you are trying to add to the set are the same thing as determined by hashcode. If this is the case, you'll need to override hashcode().

zmf
  • 9,095
  • 2
  • 26
  • 28
0

HashSet relies on the hashCode() method in Object. If you need a hash code, you need to override this method. When overriding hashCode(), one must also override equals(). See What issues should be considered when overriding equals and hashCode in Java?

Community
  • 1
  • 1
bstempi
  • 2,023
  • 1
  • 15
  • 27