list to store objects

Asked

Viewed 110 times

0

well, I’m creating a manufacturer’s list and I have a question regarding which collection to use.

I want to add several manufacturers in my list, in case I use the LIST interface Arraylist? or some in the SET interface that does not allow duplication?

  • List is only interface, there is no implementation, arraylist that is the implementation of List. Your question is based on opinion, who can decide what is best for your application is only yourself.

1 answer

1


It depends on what features you want in your collection. Basically the differences between a Set<T> and a List<T> sane:

  • A List<T> accepts duplicate elements, already a Set<T> nay;
  • A List<T> is mandatorily ordered while in a Set<T> this is optional and depends on the implementation. Example: the elements of a HashSet<T> are not ordered, but the elements of a TreeSet<T> shall be ordered in accordance with Comparator<T> defined.
  • A List<T> allows you to access elements through your position, a Set<T> does not allow this.

So just see what features you need and choose the most suitable collection. In your case, it probably doesn’t make sense to have duplicate manufacturers in your collection, so a Set<T> would be the best option.

It is also important to note that a Set<T> checks whether duplicates exist in the collection using the methods hashCode and equals. So depending on what you consider to be equal objects in your domain, you would need to override these methods so that the Set<T> identify duplicates in a correct way.

Moreover, by the form that a Set<T> works, the use of mutable elements is discouraged, since, from the moment an object is changed, the result of the methods hashCode and equals can also be changed. And in this scenario, the behavior of a Set<T> is not specified.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.