If you're using a List
you have to iterate over it to check if an object with a certain ID exists.
If you're using a Map<String, Student>
(as mentioned by Andres), where the key of the map is your ID, you can easily use containsKey(String id)
Question
I'm trying to make a program where the user enters personal info to a form which gets saved as an ArrayList object with String variables and saves it to a file. I want this file to be saved even when the program is closed, and when a new person enters their info it creates a new ArrayList and appends into the file.
My problem is trying to make a "search" function that lets you search your ID number and figures out if you're information is already in the file. This is my ActionListener method:
public void actionPerformed(ActionEvent e)
{
strID = tfID.getText();
strName = tfName.getText();
strYear = tfYear.getText();
strSubject = tfSubject.getText();
dblGPA = Double.parseDouble(tfGPA.getText());
strComment = tfComment.getText();
Student newStudent = new Student(strID, strName, strYear, strSubject, dblGPA, strComment);
ArrayList<Student> studentInfo = new ArrayList<Student>();
studentInfo.add(newStudent);
try {
writeFile(studentInfo);
System.out.println(loadFile().toString());
} catch (IOException e1) {
e1.printStackTrace();
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
}
Then my Write and Read methods:
public static void writeFile(ArrayList<Student> studentInfo) throws IOException {
FileOutputStream fos = new FileOutputStream(new File("studentlog.dat"), true);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(studentInfo);
oos.close();
}
public static ArrayList<Student> loadFile() throws IOException, ClassNotFoundException {
FileInputStream fis = new FileInputStream(new File("studentlog.dat"));
ObjectInputStream ois = new ObjectInputStream(fis);
ArrayList<Student> sAL = (ArrayList<Student>) ois.readObject();
ois.close();
return sAL;
}
Now I just need an ActionListener method for a search button that will search the ID number from the JTextField tfSearch, then compare it to existing ID numbers in the file. I feel like I'm doing something horribly wrong but it could just be a dumb mistake.
Solution
If you're using a List
you have to iterate over it to check if an object with a certain ID exists.
If you're using a Map<String, Student>
(as mentioned by Andres), where the key of the map is your ID, you can easily use containsKey(String id)
OTHER TIPS
Instead of an ArrayList, use a Map where the key is the id, and the value is the student. That will simplify the searchs a lot.
Map<String, Student> studentMap = new HashMap<String, Student>()