Re: how to search an array of objects?
Digging4fire@hotmail.com wrote:
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.
Brandon McCombs wrote:
loop through the array comparing the student name string with the text
the user enters into the textfield. After a match is found grab all data
from the array element and put them into other textfields or display the
data as text in a jlabel.
There is a utility class java.util.Arrays
<http://java.sun.com/j2se/1.5.0/docs/api/java/util/Arrays.html>
that might interest you, particularly its sort() and binarySearch() methods.
depending on how many students there are you may need to use something
other than an array so it is quicker, like a hashmap.
But this is truly the better way to go, and not just for speed or for a
particular size but because it is a more elegant and stable program construct.
It is worth knowing as much as you can about the Collections framework.
Let us pretend you call your student object type Student, defined like:
package eg;
public class Student
{
private String name;
public String getName() { return name; }
public void setName( String name ) { this.name = name; }
private int module;
public int getModule() { return module; }
public void setModule( int module ) { this.name = module; }
private float mark;
public float getMark() { return mark; }
public void setMark( float mark ) { this.name = mark; }
}
Then in your business logic class, let's call it Busy, you might use this type
in a method and associated data structure like this:
package eg.test;
import eg.Student;
public class Busy
{
...
private final Map<String, Student> enrollment =
new HashMap<String, Student> ();
public void enroll( Student student )
{
enrollment.put( student.getName(), student );
}
public Student getStudent( String name )
{
return enrollment.get( name );
}
...
}
As you see, these methods are pretty thin wrappers around the Map methods, but
this example simplifies. The purpose is to show the Map idiom, rather than to
propose one actually write such wrapper methods.
- Lew