| Author |
Colletion class to to find unique elements
|
Ashuthosh san
Ranch Hand
Joined: Jan 28, 2009
Posts: 35
|
|
Hi All,
I need some solution for the below scenario,
I have an array Temp[], this stores data as a name value pair eg: {name=name value=A; name=city value=B; name=state value=C} - Temp[0]
{name=name value=X; name=city value=Y; name=state value=Z} - Temp[1]
{name=name value=L; name=city value=M; name=state value=N} - Temp[2]
I have to check the unique count of the entries in this array. How do i do it? Please let me know. If the array contains
{name=name value=A; name=city value=B; name=state value=C} - Temp[3], It should consider this as duplicate entry in that array. Which collection class do i need to store this kind of data.
Thanks,
San
|
 |
Seetharaman Venkatasamy
Bartender
Joined: Jan 28, 2008
Posts: 4503
|
|
|
what about HashSet? [contains method of Set]
|
Not everything that counts can be counted, and not everything that can be counted counts-Albert Einstein
|
 |
Ashuthosh san
Ranch Hand
Joined: Jan 28, 2009
Posts: 35
|
|
Hi,
I even tried using HashSet, its not working.
Temp[] t ; Which has the data
Set set = new HashSet(Arrays.asList(t));
Temp[] uniqueArray = (Temp[])(set.toArray(new Temp[set.size()]));
return uniqueArray.length;
Please suggest me some solution. Do i need to override equals method. But here Temp class is a final class so i can not override it also.
Regards
San
|
 |
D. Ogranos
Ranch Hand
Joined: Feb 02, 2009
Posts: 181
|
|
Set is a collection type thats supposed to not contain duplicates. It ensures this with the equals() method of the objects in the set. You probably need to overwrite the equals() method of your data class for this to work correctly (I assume that you represent the data in your array as a data class). It may also be neccessary to overwrite the hashCode() method...see the documentation on equals() and hashCode().
Btw. if you keep your data in a Set, you don't need to convert it to an array to get the size, just call set.size() then.
|
 |
Ashuthosh san
Ranch Hand
Joined: Jan 28, 2009
Posts: 35
|
|
Thanks,
But that data class is a final class and is implemented by other person. So please suggest any alternate solution for this problem.
|
 |
D. Ogranos
Ranch Hand
Joined: Feb 02, 2009
Posts: 181
|
|
If you have no way to change the data class, you could create a wrapper class for the data, and override the equals() (and perhaps hashCode() too) in that wrapper class. Just an idea.
|
 |
Rob Spoor
Saloon Keeper
Joined: Oct 27, 2005
Posts: 18365
|
|
A TreeSet doesn't use equals / hashCode but compareTo, or a custom Comparator. And that last one can help you out.
The comparator needs to compare on all fields though. For instance:
If this Comparator's compare method returns 0 (i.e. the name, city and state are equal) then a new element is not added.
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
 |
|
|
subject: Colletion class to to find unique elements
|
|
|