You're hitting this warning spelled out in the javadocs for ArrayList: The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future. What this means is you can't iterate through an ArrayList using a for loop and remove elements in that for loop. You can use an iterator to solve this. Call ArrayList.iterator() and use Iterator.remove() to do the removal. Iterator iter = phonebook.iterator(); while (iter.hasNext()) { Entry entry = iter.next(); if (entry.getFirstName().equalsIgnoreCase(string)) { iter.remove(); } } It's a bit clunky but that's how you modify a collection during iteration. Answer from Northeastpaw on reddit.com
๐ŸŒ
Reddit
reddit.com โ€บ r/javahelp โ€บ how to remove object from arraylist depending on attribute?
r/javahelp on Reddit: How to remove object from ArrayList depending on attribute?
April 30, 2019 -

I am creating a phone book program and need a method to remove an entry from the directory depending on what name or phone number the user enters.

So far I have the following code:

public void deleteEntry(String string) {
        for(Entry e : phonebook){
            if (e.getFirstName().equalsIgnoreCase(string)){
                phonebook.remove(e);
                System.out.println("Entry " + e.toString() + " removed");
            }
            else {
                System.out.println("Entry not deleted");
            }
        }
    }

Which I thought should work, however it gives the following errors. The program outputs the deletion message as well which is weird so I am not sure what is causing this error.

The code the method is being called in is shown here:

                case 2:
                    printDirectory();
                    System.out.println("Enter name or number: ");
                    String nameOrNum = input.nextLine();
                    deleteEntry(nameOrNum);
                    break;

I have an Entry class which contains information for a single Entry object. Is there a way I could override the equals() method to compare first names and implement the delete method this way? Or can my solution be resolved easily?

Thanks in advance!

๐ŸŒ
DigitalOcean
digitalocean.com โ€บ community โ€บ tutorials โ€บ java-list-remove-methods-arraylist-remove
How To Use remove() Methods for Java List and ArrayList | DigitalOcean
September 9, 2025 - There are two remove() methods to remove elements from the List. ... index): This method removes the element at the specified index and returns it. The subsequent elements are shifted to the left by one place. This method throws IndexOutOfBoundsException if the specified index is out of range. If the list implementations does not support this operation, UnsupportedOperationException is thrown. ... o) This method removes the first occurrence of the specified Object.
๐ŸŒ
W3Schools
w3schools.com โ€บ java โ€บ ref_arraylist_remove.asp
Java ArrayList remove() Method
If the list contains integers and you want to delete an integer based on its value you will need to pass an Integer object. See More Examples below for an example. ... T refers to the data type of items in the list. Remove an integer from the list by position and by value: import java.util.ArrayList; public class Main { public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<Integer>(); list.add(5); list.add(8); list.add(9); list.add(1); list.remove(Integer.valueOf(1)); // Remove by object list.remove(1); // Remove by index System.out.println(list); } }
Top answer
1 of 4
8

If you change the class Item equals() and compareTo() methods, so that they check only one object field, such as a quantity, it could result in strange behavior in other parts of your application. For example, two items with different itemNo, itemName, and itemPrice, but with the same quantities could be considered equal. Besides, you wouldn't be able to change the comparison attribute without changing the equals() code every time.

Also, creating a custom contains() method makes no sense, since it belongs to the ArrayList class, and not to Item.

If you can use Java 8, a clean way to do it is to use the new Collection's removeIf method:

Suppose you have an Item class with the num and name properties:

class Item {
    final int num;
    final String name;

    Item(int num, String name) {
        this.num = num;
        this.name = name;
    }
}

Given a List<Item> called items and an int variable called number, representing the number of the item you want to remove, you could simply do:

items.removeIf(item -> item.num == number);

If you are unable to use Java 8, you can achieve this by using custom comparators, binary search, and dummy objects.

You can create a custom comparator for each attribute you need to look for. The comparator for num would look like this:

class ItemNumComparator implements Comparator<Item> {
    @Override
    public int compare(Item a, Item b) {
        return (a.num < b.num) ? -1 : ((a.num == b.num) ? 0 : 1);
    }
}

Then you can use the comparator to sort and search for the desired elements in your list:

public static void main(String[] args) {
    List<Item> items = new ArrayList<>();
    items.add(new Item(2, "ball"));
    items.add(new Item(5, "cow"));
    items.add(new Item(3, "gum"));

    Comparator<Item> itemNumComparator = new ItemNumComparator();
    Collections.sort(items, itemNumComparator);

    // Pass a dummy object containing only the relevant attribute to be searched
    int index = Collections.binarySearch(items, new Item(5, ""), itemNumComparator);
    Item removedItem = null;
    // binarySearch will return -1 if it does not find the element.
    if (index > -1) {
        // This will remove the element, Item(5, "cow") in this case, from the list
        removedItem = items.remove(index);
    }
    System.out.println(removedItem);
}

To search for another field like name, for example, you would need to create a name comparator and use it to sort and run the binary search on your list.

Note this solution has some drawbacks though. Unless you are completely sure that the list didn't change since the last sort, you must re-sort it before running the binarySearch() method. Otherwise, it may not be able to find the correct element. Sorting complexity is O(nlogn), so running it multiple times can get quite expensive depending on the size of your list.

2 of 4
1

Do you want to remove an object at a specific index? I'm not entirely sure what you mean by 'number field'. If so, jump to method: remove(int):

http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#remove%28int%29

EDIT: If you want to find/adjust a field of an object in the Array list, you can do this (piece of my own code):

public boolean studentHasISBN(ArrayList<Student> st, String s){
    for(Student j : st) {
        if(s.equals(j.getRentedBookISBN()))
            return true;
    }
    return false;
}

All you have to do is iterate through the list, and search through the field that you want to find. Then use the remove(int) method.

Find elsewhere
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ remove-elements-from-a-list-that-satisfy-given-predicate-in-java
Remove elements from a List that satisfy given predicate in Java - GeeksforGeeks
September 23, 2018 - If an element does not satisfy ... shows how to remove specific elements from a List in Java using a Predicate and the removeAll() method....
Top answer
1 of 1
2

You have many, many bugs in this code.

2 scanners

You should have only one Scanner object. Why do you have both kb and in? Delete one.

mixing nextLine and nextAnythingElse

You can't mix those. The usual thing to do is to never use nextLine(); to read a line of text, just use next(). This does require that you update the scanner's delimiter; immediately after making the scanner object, call in.useDelimiter("\r?\n"); on it.

AList isn't a thing

Whatever might 'AList' be? It's not in core java and it doesn't sound like it is required here; just use ArrayList<Patient> instead

naming a class with a plural name.

Clearly a single Patients instance represents a single patient, therefore, you should call it Patient, because what you have is clearly confusing you.

You're breaking with convention.

thisIsAVariableName, ThisIsATypeName, THIS_IS_A_CONSTANT. That should be aPatients, not APatients. This makes your code hard to read, and given that you're using a community resource (Stack Overflow), that's not good.

Your actual question

Given that AList is not a thing and you didn't paste it, it is not possible for anybody on SO to answer this question. Update the question and include the API of AList, or stop using it (there is no reason to use this, unless it is mandated because this is homework, in which case, you should ask your teacher for help on this; they get paid, and are the ones who are supposed to support this AList class you're using). Had you been using ArrayList, there are a number of ways to do this. But first a concern: If you loop through each item by way of 'index', then removing an element shifts all indexes down by one, which makes the math complicated. One extremely easy way out of that dilemma is to loop through the list backwards to forwards, because then the shifting of indices doesn't have an impact.

Option #1: Iterators

var it = aPatients.iterator();
while (it.hasNext()) {
    Patient p = it.next();
    if (p.getAge() > 25) it.remove();
}

Option #2: Backwards loop

for (int i = aPatients.size() - 1; i >= 0; i--) {
    if (aPatients.get(i).getAge() > 25) aPatients.remove(i);
}

Option #3: removeIf

aPatients.removeIf(pat -> pat.getAge() > 25);
๐ŸŒ
Java67
java67.com โ€บ 2014 โ€บ 03 โ€บ 2-ways-to-remove-elementsobjects-from-ArrayList-java.html
2 Ways to Remove Elements/Objects From ArrayList in Java [Example] | Java67
By the way, You should always use remove(index) to delete objects, if you are not iterating, otherwise, always use Iterator's remove() method for removing objects from ArrayList. By the way, the above tips will work with any index-based List ...
๐ŸŒ
Coderanch
coderanch.com โ€บ t โ€บ 638987 โ€บ java โ€บ Deleting-complex-object-Java-list
Deleting complex object in Java list (Beginning Java forum at Coderanch)
Start by looking for the three resources in this thread. Also search this forum and Java in General; there was a long discussion about it about two months ago. ... I did it this way, and within "Test Web Service" (with manual imputs of courrse) it works (I can get, add and remove countries, i.e. objects).
๐ŸŒ
BeginnersBook
beginnersbook.com โ€บ 2013 โ€บ 12 โ€บ java-arraylist-removeobject-method-example
Java ArrayList remove(Object obj) Method example
We can remove a specific string from the list using remove() method. import java.util.ArrayList; public class RemoveExample { public static void main(String args[]) { //String ArrayList ArrayList<String> al = new ArrayList<>(); al.add("AA"); al.add("BB"); al.add("CC"); al.add("DD"); al.add("EE"); ...
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ home โ€บ java/util โ€บ java arraylist remove object
Java ArrayList Remove Object
September 1, 2008 - The following example shows the usage of java.util.ArrayList.remove(object) method. package com.tutorialspoint; import java.util.ArrayList; public class ArrayListDemo { public static void main(String[] args) { // create an empty array list with an initial capacity ArrayList<String> arrlist = new ArrayList<String>(5); // use add() method to add values in the list arrlist.add("G"); arrlist.add("E"); arrlist.add("F"); arrlist.add("M"); arrlist.add("E"); System.out.println("Size of list: " + arrlist.size()); // let us print all the values available in list for (String value : arrlist) { System.out.println("Value = " + value); } // Removes first occurrence of "E" arrlist.remove("E"); System.out.println("Now, Size of list: " + arrlist.size()); // let us print all the values available in list for (String value : arrlist) { System.out.println("Value = " + value); } } }
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ list-removeobject-obj-method-in-java-with-examples
List remove(Object obj) method in Java with Examples - GeeksforGeeks
November 29, 2024 - The remove(Object obj) method of List interface in Java is used to remove the first occurrence of the specified element obj from this List if it is present in the List.
Top answer
1 of 2
2

As per the JavaDoc:

public boolean remove(Object o)

Removes the first occurrence of the specified element from this list, if it is present. If the list does not contain the element, it is unchanged. More formally, removes the element with the lowest index i such that (o==null ? get(i)==null : o.equals(get(i))) (if such an element exists). Returns true if this list contained the specified element (or equivalently, if this list changed as a result of the call).

Which essentially means that borrowers.remove(libraryNumber); will work if and only if you have some Borrower object which is equal to that string. Unless you have added an override to the equals method in your Borrower class, it is unlikely that this will ever work. Thus, you have two options:

  1. Override the equals (and for good practice, the hashcode()) methods within your Borrower class such that two borrower items are considered equal if they have the same libraryNumber.

  2. The second option would be to use an iterator to go through your Borrower items stored within borrower and use the iterator's remove method to delete the objects which have the same property values.

As a side note, although the first approach might be more elegant for some, caution must be taken since in your particular scenario, Borrower objects might not be equal just because they have the same libraryNumber.

2 of 2
0
public boolean removeBorrower(String libraryNumber)
{
    boolean retVal = false;
    if(borrowers.contains(libraryNumber))
    {
       retVal = borrowers.remove(libraryNumber);
    } 
    return retVal;
}

Something like this perhaps? I know it's a long round-about way of doing things, since the easiest way would be

public boolean removeBorrower(String libraryNumber)
{
       return borrowers.remove(libraryNumber);
}

But perhaps I don't quite understand what's the problem you're having?

๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ how-to-remove-an-element-from-a-java-list
How to remove an element from a Java List?
The remove(object) method of the List interface is used to remove the first occurrence of the specified element (i.e., object) from the list if it is present.