hat_to_the_back
hat_to_the_back

Reputation: 99

Sets and ArrayLists

If I have an ArrayList of object type and I want to get the name of a particular object I would use

arraylist.get(i).getName();

But it does not work with Sets? How do I call the particular attribute using Sets?

Also reason I am trying to do this is because Im handling a lot of data. How much more efficient

are Sets?

Upvotes: 0

Views: 71

Answers (4)

laune
laune

Reputation: 31290

A List (ArrayList) is indicated if

  • the order of the list elements matters
  • if multiple instances of equal elements are to be inserted
  • you can (reasonably) access elements using the index values 0, 1, 2,...
  • fast iteration over all values is important

A Set (HashSet) is preferable if

  • each instance of equal elements should be represented only once
  • you don't care about insertion order
  • you don't need to retrieve by an index (or some other property)

To access a property of the elements in a Set, you can (or have to) iterate over the Set elements (in no particular order) and call the getter:

Set<Element> setOfEl = ...;

for( Element el: setOfEl ){
    if( el.getName().equals( ... ){
        //....
    }

. }

Upvotes: 1

tempusfugit
tempusfugit

Reputation: 437

ArrayList<E>, as the name says, is a List<E>, hence the method get(i) gives you an object of type E. Set<E> do not have such method hence getName() will not work.

Set<E> is not ordered. You have to use an Iterator to parse a Set and traverse all of its elements.

You can refer to the documentation here:

Upvotes: 0

Thickfreakness
Thickfreakness

Reputation: 21

If you need to grab particular elements then an array/arraylist is a better implementation. Though if you really need to you sets you could itterate through the set with a for loop, like:

for(MyObject elem : mySet){
  elem.getName();//Do something with each name
}

To grab each name.

Upvotes: 2

Miquel
Miquel

Reputation: 15675

The problem is not with getName() but with getting the object on which you call getName(). In the case of an ArrayList, you can call get(i) to get the i-th element. In the case of a set, no such order is defined.

You have two choices. Either you define it as a Map and you call get(<yourkey>) and then call getName(), or you iterate through the set until you find what you are looking for using .iterator()

Upvotes: 0

Related Questions