I have a main class that creates an arraylist of type Element:
public static void main(String[] args) throws IOException {
String input = "";
String id = ""; //combination of letters and numbers
String name = "";
ArrayList<Element> element = new ArrayList<> ();
BufferedReader in = new BufferedReader( new InputStreamReader(System.in));
while(!(input.equalsIgnoreCase("quit"))) {
System.out.println("Please enter 'e' to enter an element, or 'quit' to quit");
input = in.readLine();
if(input.equalsIgnoreCase("e")) {
System.out.println("Please enter a name for the element");
name = in.readLine();
System.out.println("Please enter an id for the element");
id = in.readLine();
element.add(new Element(name,id));
//only add if id and name don't exist already
}
}
}
Then I have a element clas:
public class Element {
private String name;
private String id;
public Element(String name, String id) {
this.name = name;
this.id = id;
}
}
I want to check before adding an element to a list (it's id and name), to check if another element already in the list already has those exact values (id and name). I know I can use the toString method to do this, but I'm not sure how I can override it to pass on an id and name, before adding the elements to the list. Is their a way to do this? Ideally I'd only want to add an element, if it doesn't already exist.