Dave
Dave

Reputation: 23

Searching for a specific element in a TreeSet

I am attempting to search for Member with a specific regNumber within a TreeSet. The regNumber however doesn't have anything to do with the order of the elements in the TreeSet , which are ordered by last/first name.

The way I'm trying to do it now is to iterate through all the elements in TreeSet and return the element that matches the regNumber I am looking for. Is that good practice or is it too inefficient?

public class Members implements Comperable <Members> {

private String firstName;
private String lastName;
private int regNumber;

}

P.S the elements in the TreeSet must remain ordered by last/first name

Upvotes: 2

Views: 548

Answers (1)

Tudor
Tudor

Reputation: 62439

That fact that you are indexing by name and then searching by regNumber means that from the point of view of the regNumber you have an unordered collection of items. Therefore, you cannot do better than a linear search over all the items.

If you want something better you could use the regNumber as a key in a hash table (HashMap or whatever) and have a reference to the original Member object as value. That way you can search more efficiently at the cost of using more space.

Upvotes: 8

Related Questions