1

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;
}
de_dust
  • 291
  • 5
  • 13
  • Why is this a Set instead of a Map from names to whatevers? – user2357112 Dec 17 '16 at 00:50
  • @user2357112: Because this is an assignment and I'm not allowed to change the collection. – de_dust Dec 17 '16 at 00:51
  • Then the assignment probably either expects you to use O(n) lookup, or expects you to avoid performing these lookup operations. There's also the possibility that you're supposed to build and maintain an auxiliary map, or that the assignment is inconsistent, or that you've misunderstood something. – user2357112 Dec 17 '16 at 00:57
  • Theoretically speaking, there's also an awful hack involving equal-but-not-really elements and tailSet, but that's quite unlikely to be what the assignment is looking for, and a good grader would probably take style points off for that. – user2357112 Dec 17 '16 at 01:00
  • @user2357112: Well, I'll just have to use O(n) then... I thought I could optimize it a little. – de_dust Dec 17 '16 at 01:03

2 Answers2

0

In general, our existing TreeSet<Person> cannot be used for lookup by name. The treeset will be organized based on the what ever ordering you have defined for the set.

In general, you need is a separate Map<String, Person> that holds mappings for all of the Person objects in the original set. This entails keeping the set and the map in step.

However, if the ordering of your tree set was a combination of name and age, with the name providing the major ordering, then you could use TreeSet.tailSet to get the "tail" of the set starting with a given name. Then iterate the tail set until the name changes.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
0

The TreeSet arranges items based on its Comparator.

You can implement the comparison operation to be sorted by name first.

Thilo
  • 257,207
  • 101
  • 511
  • 656