Removing an item from an ArrayList via Iterator

I want to take a look at the entry in the ArrayList and delete the element if it is found, the easiest way, in my opinion, is through Iterator , here is my code:

  for (Iterator<Student> it = school.iterator(); it.hasNext();){ if (it.equals(studentToCompare)){ it.remove(); return true; } System.out.println(it.toString()); it.next(); } 

But something is wrong: instead of iterating through my ArrayList<Student> school I get it.toString() using:

 java.util.ArrayList$Itr@188e490 java.util.ArrayList$Itr@188e490 ... 

What's wrong?

+4
source share
4 answers

Why not?

 school.remove(studentToCompare); 

Use the remove (Object) list.

Removes the first occurrence of the specified item from this list, if present (optional operation).

And more than that

It returns true if this list contains the specified element (or, what is the same, if this list has changed as a result of a call).

+13
source

it is Iterator , not Student

 for (Iterator<Student> it = school.iterator(); it.hasNext();){ Student student = it.next(); if (student.equals(studentToCompare)){ it.remove(); return true; } System.out.println(student.toString()); } 
+19
source

The reason you get this output is because you are calling the toString() method on the iterator and not on the Student object.

You can remove Student from the list using

 school.remove(student); 

Also, if you want to print meaningful information about the Student object when writing

 System.out.println(student); 

Override the toString() method for it, because the System.out.println() statement will internally call toString() on the Student object.

 public String toString() { return "Student [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + "]"; } 
+1
source
 for (Iterator<Student> it = school.iterator(); it.hasNext();){ **Student st** = it.next(); if (**st**.equals(studentToCompare)){ it.remove(); return true; } System.out.println(**st**.toString()); } 

OR

 school.remove(school.indexOf(studentToCompare)); 

OR

 school.remove(studentToCompare); 

The last two examples suggest that school is a List .

+1
source

Source: https://habr.com/ru/post/1486380/


All Articles