I have a TreeSet where the elements are Objects with two attributes (Name and Age). Every time I want to search for an object with a specific name, I have to resort to a enhanced for loop or an iterator.
I can't use the contains()
method to search for an object with a specific name, because the name is "encapsulated" within this object.
Is there a way to overcome this problem? That is, a way to take advantage of the log(n)
time complexity of contains()
?
Since all elements in the TreeSet are sorted by name, there must be a way I think.
An example of what I want to achieve:
public Element search(String name) {
// if some TreeSet element's name.equals(name), return the Element
}
An example of what I don't want to use:
public Element search(String name) {
for (Element entry : tree) {
if (entry.getName().equals(name)) {
return entry;
}
}
return null;
}