Re: how to search an array of objects?
Digging4fire@hotmail.com wrote:
hi all,
hope someone can help.
i have created a array of student objects -
each object has a string for student name
a float for mark
and a int for module number.
i need to be able to display the details for a paticular student when
the user types in the student name. so i'm thinking i need some way of
searching the array of student objects for a particular string and then
extract all details relating to that oject? not sure how though.
tia.
Searching:
private Student[] students;
public Student findStudent(String name) {
/* for every Student in the array */
for (Student student: students) {
/* Does the student have the right name */
if (student.name.equals(name)) {
/* found the student */
return student;
}
}
/* didn't find the student */
return null;
}
Although, a better approach would be:
public class StudentRecords {
private Map<String, Student> studentByName
= new HashMap<String, Student>();
private Student[] students;
public StudentRecords(Student...students) {
this.students = students;
for (Student student: students) {
studentByName.put(student.name, student);
}
}
public Student findStudent(String name) {
return studentByName.get(name);
}
/* any other useful methods follow */
}