File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes List and Set in one Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "List and Set in one" Watch "List and Set in one" New topic

List and Set in one

Ronwaldo Cruz
Ranch Hand

Joined: Oct 17, 2006
Posts: 69

What do you usually use when you need a collection that is unique (like a Set) but has indexes (like a List)?
Ulf Dittmer

Joined: Mar 22, 2005
Posts: 42965
Maybe write a subclass of ArrayList that enforces the uniqueness of elements. There are probably ready-made classes like that out there.
Fahd Shariff
Ranch Hand

Joined: Nov 22, 2002
Posts: 38
Use a LinkedHashSet

Fahd Shariff<br />"Let the code do the talking"
Bear Bibeault
Author and ninkuma

Joined: Jan 10, 2002
Posts: 63870

Fahd Shariff wrote:Use a LinkedHashSet

While LinkedHashSet will retain the iteration order, it is not indexable. That would have to be added.

I'd still go with Ulf's approach as it's easier to add uniqueness to a List than index-ability to a Set.

[Asking smart questions] [About Bear] [Books by Bear]
I agree. Here's the link:
subject: List and Set in one
It's not a secret anymore!