I have a class that contains two arraylists- student names and Ids
I want to put them into LinkedHashSet( so, I can sort, delete, add and edit e student profile);
I created a class called Student that contains setName getName setId getId and toString methods.

now, I try to do something like

LinkedHashSet<Student> list=new LinkedHashSet<Student>();

for(String i:Array.studentName){
    for(int j:Array.studentId){
         student(i,j);// for loop seems doesn't work here. the student name repeats and repeats
         list.add(student);

I don't know if I am on the track or not. any suggestion? Thanks

Edited 5 Years Ago by Ezzaral: Added code tags. Please use them to format any code that you post.

You have 2 nested loops, which will get you every possible combination of name & id.
But what you want is just the matching name & id for the same student - something like

for i = 0 to (number of students)
  list.add (new Student(studentName.get(i), studentID.get(i))
...

for (Student s : list) {
  System.out.println(s.getName() + s.getID());

apart from that... yes, you are on the right track.

Thanks JamesCherrill. This is my delete method. can you see any errors? It outputs "not in the list"(I double checked my input and compare to the item in the list. Im sure they are exactly same.

String st;
String st2;
st=JOptionPane.showInputDialog("Enter a name (Ex: James Acosta)");
st2=JOptionPane.showInputDialog("Enter the student ID(Ex: 12345678)");
Student onestudent=new Student(st,st2);
for(Object pn:human){ 
     if(pn.equals(onestudent)==true{
         System.out.println("in the list");
		}
     else if(pn.equals(onestudent)==false){
	System.out.println("not in the list");
				}
				
				
			}

Edited 5 Years Ago by newbieha: n/a

if(pn.equals(onestudent)==true
1. the == true is totally redundant.
if(pn.equals(onestudent)
the equals method inherited from Object compares pn and onestudent to see if they are exactly the same Object. But onepperson is a new Student object that you just created, so it's never the same Object.
What you need to do is to override the equals method in your Student class so equals means what you want it to mean (ie two Student objects represent the same student if they both have the same name and ID). This is standard stuff - eg the String class overrides equals to return true if both Strings contain the same sequence of characters.

This article has been dead for over six months. Start a new discussion instead.