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
That fact that you are indexing by name and then searching by
regNumbermeans that from the point of view of theregNumberyou 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
regNumberas a key in a hash table (HashMapor whatever) and have a reference to the originalMemberobject as value. That way you can search more efficiently at the cost of using more space.