1

I have an ArrayList<Card> cards = new ArrayList<Card> which I need to convert into TreeSet<Card>. For this purpose I do:

new TreeSet<Card>(cards)

After all I have a size of the TreeSet equal to 1. The Card class implements Comparable interface. What I'm doing wrong or not doing?

3 Answers 3

7

If all of the Cards in the ArrayList evaluate to equal using the provided Comparable interface (i.e. compare always returns 0) then you will end up with just one entry in your TreeSet.

Sign up to request clarification or add additional context in comments.

1 Comment

This solution works. Check this operation Card.compareTo(Card card)
2

They implement Comparable, but how? In a TreeSet, elements for which a.compareTo(b) returns 0, only the first is added.

2 Comments

More likely only the last will be retained but that is just pedantry on my part.
@OldCurmudgeon just for pedantry, I tried: Long a = Long.valueOf(123456789012345L); Long b = Long.valueOf(123456789012345L); assertNotSame(a,b); TreeSet<Long> s = new TreeSet<>(Arrays.asList(a,b)); assertEquals(1, s.size()); assertSame(a,s.first());
-1

Easiest way to convert a List to a Set? - Java

Set<Foo> foo = new HashSet<Foo>(myList);

TreeSet tSet = new TreeSet(myList);

2 Comments

it's about a Treeset, not a HashSet.
Pass the ArrayList to Treeset. There is a constructor in Treeset that accept Collection.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.