| Author |
Count duplicates in a TreeSet Collection
|
Quiddo Quitch
Ranch Hand
Joined: Apr 21, 2008
Posts: 38
|
|
i was wondering, is there anyway to know how many duplicates were detected in a TreeSet Collection ?
for example in the following code there are 3 duplicates ... is there anyway to get that value ?
thanks !!
|
 |
Christophe Verré
Sheriff
Joined: Nov 24, 2005
Posts: 14672
|
|
|
Methods usually return some useful information. Did you check what the add method of java.util.TreeSet returns ?
|
[My Blog]
All roads lead to JavaRanch
|
 |
Quiddo Quitch
Ranch Hand
Joined: Apr 21, 2008
Posts: 38
|
|
yes i checked the returns methods, i have the method "size()" to determine the number of elements in the collection, but that not give me the number of duplicates
|
 |
Quiddo Quitch
Ranch Hand
Joined: Apr 21, 2008
Posts: 38
|
|
i figure it out, you can close this thread ...
the solution is to count all elements and then rest it to size() method ... finally you get the duplicates number
|
 |
K. Tsang
Ranch Hand
Joined: Sep 13, 2007
Posts: 1222
|
|
|
A set contains no duplicates. So the size() method won't help. In fact what does add() returns? boolean right? Now does add return false if you add integer 1 the 2nd time? if so you can have a variable to keep track of this and will return 3 in your code.
|
K. Tsang JavaRanch SCJP5 SCJD/OCM-JD
|
 |
Mike Simmons
Ranch Hand
Joined: Mar 05, 2008
Posts: 2782
|
|
What if you count how many times add() was called? Then if, for example, add() was called 35 times, but the final size() is 28, there must have been 7 duplicates.
Or, what if you counted how many times add() returned true?
|
 |
Quiddo Quitch
Ranch Hand
Joined: Apr 21, 2008
Posts: 38
|
|
K. Tsang wrote:A set contains no duplicates. So the size() method won't help. In fact what does add() returns? boolean right? Now does add return false if you add integer 1 the 2nd time? if so you can have a variable to keep track of this and will return 3 in your code.
i used a List to count the total results and a Set to have no duplicates ... then i got the size() of List minus the size() of Set ... this is probably not the smartest way, but it worked like a charm xD
|
 |
Christophe Verré
Sheriff
Joined: Nov 24, 2005
Posts: 14672
|
|
this is probably not the smartest way
Surely not You misunderstood my hint. K. Tsang described what I wanted to tell you : use add()'s return value to determine if an element was added or not.
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
|
Perhaps you should use a org.apache.commons.collections.Bag
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
 |
|
|
subject: Count duplicates in a TreeSet Collection
|
|
|