Eugene
Eugene

Reputation: 60184

Converting ArrayList into TreeSet

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?

Upvotes: 1

Views: 8495

Answers (3)

sarath
sarath

Reputation: 893

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

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

TreeSet tSet = new TreeSet(myList);

Upvotes: -1

GeertPt
GeertPt

Reputation: 17854

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

Upvotes: 2

OldCurmudgeon
OldCurmudgeon

Reputation: 65811

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.

Upvotes: 7

Related Questions