Reputation: 1801
What's the recommended way to ensure all the items of an ArrayList list are unique either by extending the ArrayList or using another container?
class ProList extends ArrayList
{
public <E> boolean super_add(E e)
{
if(this.contains(e)) {
System.out.println("Item not added because it exists already.");
return false;
}
else
return this.add(e);
}
};
The above works but it's full of warnings and sees a bit hacky...
Upvotes: 0
Views: 107
Reputation: 11867
If you don't have to use an ArrayList
, I'd recommend checking out Java's Set interfaces. A regular HashSet would likely offer you the best performance. TreeSet would work if you want elements to maintain logical order. LinkedHashSet would work if you want to maintain insertion order, as if it were an ArrayList
. You'll have to override equals()
to use any set, and to use the hash-based sets, you'll need to also override hashCode()
.
Upvotes: 2
Reputation: 24192
if you want to maintain insertion order and uniqueness (as defined by hashCode() and equals(), which you will need to properly override and implement in any classes going into the colelction), use LinkedHashSet
Upvotes: 4