0

I wanted to know if items can be removed from a list while iterating the list using a for loop. What would be the best way to do this? Here's my code:

public static void adder(List<String> batchNumber) {
 for (String num : batchNumber) {
    Scanner obj = new Scanner(System.in);  
    System.out.println("batchnumber you want to remove: ");
    String answer = obj.nextLine();  
    if (num==answer){
        batchNumber.remove(num);
    }
 }
}
  • Have you tried it out? --- [Never use `==` to compare `String`s (or any reference-type really) unless you know exactly what you are doing and why you are doing it](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java). – Turing85 Apr 21 '22 at 14:45
  • A lot to unpack here. 1) Why ask for the number to remove inside the loop? 2) If you want to do that, why create a new `Scanner` on every iteration? 3) Why loop at all, instead of using `indexOf()` to get the location of the item to remove? 4) This is a big one: why compare strings using `==`, when they're objects and need to be compared using `equals()`? All questions that need to be answered before we get to your actual question. – Robby Cornelissen Apr 21 '22 at 14:48
  • I'm closing in favor of a likely duplicate. If the answers to the duplicate don't answer your question, please clarify after having addressed the points in the comments. – Robby Cornelissen Apr 21 '22 at 14:53
  • public static void adder(List batchNumber) { while(batchNumber.hasNext()){ Scanner obj = new Scanner(System.in); System.out.println("batchnumber you want to remove: "); String answer = obj.nextLine(); if(batchNumber.next().getIsbn().equals(answer )){ batchNumber.remove(num); } } }An element can be removed from a Collection using the Iterator method remove(). This method removes the current element in the Collection. If the remove() method is not preceded by the next() method, then IllegalStateException's thrown. – DereckChamboko Apr 21 '22 at 14:54
  • @DereckChamboko That won't even compile. If you'd correct it to use an `Iterator`, it would work, but it's overkill for this scenario, and very old-school Java. – Robby Cornelissen Apr 21 '22 at 14:57

0 Answers0