Reputation: 99
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
Reputation: 31290
A List (ArrayList) is indicated if
A Set (HashSet) is preferable if
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
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
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
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