I'm a relative newbie to Java and am building an application for my programming course where users can enter, remove, search or edit a list of Students (an object which consists of an integer ID number, a String last name, and a double GPA). So far, I have had success with allowing the user to enter, remove, or edit entries. Right now, the list of 100+ students are in an ArrayList (each as a Student object with the three parameters).
My problem is that I don't know an efficient way to allow the user to search for a specific student based on ID number, last name, or GPA (and possibly GPA range in the future). I have been studying Big-O notation and would like to use a binary search because it would be great practice as well as a better choice if the Student list continues to grow. So far, for binary searches, we are using the high/low/mid method with a while loop (if that is any indication of my current skill level).
So here is my question:
What is an efficient way to search for a specific student based on this criteria? I am not looking for code or answers to my dilemma. I'm really looking for the names of techniques or tricks that Java programmers use to do such a thing, especially if those techniques can be used with other object-oriented programming languages.
I recommend looking into the HashMap data structure. It allows you to store elements in a collections mapped to a certain key, such that they can be later retrieved by that same key. In your example you could have different hash maps for searching on different fields. The key of the hash map would be the field (ie: ID, lastname, or GPA), and the value would be the corresponding student. For case insensitive searches, make sure to convert the key (last name) to lower case before saving an object and before retrieving an object.
to store ids:
Map<String, Student> idToStudent;
key: "23213233", value: "Some Student";
to take into account duplicate names or gpa, then use a map of type:
Map<String, List<Student>> lastNameToStudents;
key: "smith", value: ["John Smith", "Bob Smith", etc]
Map<Double, List<Student>> gpaToStudents:
key: "2.4", value: ["Student 1", "Student 2", etc];
Note, I'm using the string representation of a student's name for brevity, but in reality those represent Student
instances.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With