The problem with your code is not the removeDuplicates method. Instead is probably the equals method in the Road class. List.contains(...) uses this equals method to compare if the list contains the given element. So to make your code work as expected you should override the equals method in the Road class to perform the needed comparison. Depending on the Road class implementation this could look like this for example:

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    Road road = (Road) o;
    return Objects.equals(road.x, x) &&
            Objects.equals(road.y, y) &&
            Objects.equals(imgPath, road.imgPath) &&
            Objects.equals(color, road.color);
}

@Override
public int hashCode() {
    return Objects.hash(x, y, imgPath, color);
}

As already pointed out in the comments these methods are usually generated using your IDE and only adjusted when needed. When adjusting them you have to take into consideration that there is a contract (which can be found in the docs) between equals and hashcode which has to be considered for various reasons (for example using hashsets).

Answer from Jakob Em on Stack Overflow
Top answer
1 of 2
3

The problem with your code is not the removeDuplicates method. Instead is probably the equals method in the Road class. List.contains(...) uses this equals method to compare if the list contains the given element. So to make your code work as expected you should override the equals method in the Road class to perform the needed comparison. Depending on the Road class implementation this could look like this for example:

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    Road road = (Road) o;
    return Objects.equals(road.x, x) &&
            Objects.equals(road.y, y) &&
            Objects.equals(imgPath, road.imgPath) &&
            Objects.equals(color, road.color);
}

@Override
public int hashCode() {
    return Objects.hash(x, y, imgPath, color);
}

As already pointed out in the comments these methods are usually generated using your IDE and only adjusted when needed. When adjusting them you have to take into consideration that there is a contract (which can be found in the docs) between equals and hashcode which has to be considered for various reasons (for example using hashsets).

2 of 2
3

Make sure you have overridden equals and hashCode methods in the class, Road something like:

@Override
public boolean equals(Object obj) {
    Road other = (Road) obj;
    return Objects.equals(imgPath, other.imgPath) && Objects.equals(color, other.color)
            && Objects.equals(x, other.x) && Objects.equals(y, other.y);
}

@Override
public int hashCode() {
    return Objects.hash(imgPath, color, x, y);
}

Also, instead of writing so many lines in your method, you can write just one line using Stream API as follows:

private List<Road> removeDuplicates(List<Road> array) {
    return array.stream().distinct().collect(Collectors.toList());
}
People also ask

What is the difference between a HashSet and an ArrayList in Java?
An ArrayList keeps every element you add (duplicates included) in insertion order and is indexed by position. A HashSet stores only unique values, makes no promise about order, has no index, and its contains check is roughly constant time instead of scanning the whole list. Reach for a HashSet when you care about uniqueness or fast membership, not position.
🌐
coddy.tech
coddy.tech › docs › hashset
Runnable Java Docs: HashSet | Coddy
How do you create a HashSet in Java?
Declare it with one type parameter - the element type - and call the constructor: Set tags = new HashSet&lt;&gt;();. Add values with tags.add("java"); and test membership with tags.contains("java");. Import java.util.HashSet and java.util.Set.
🌐
coddy.tech
coddy.tech › docs › hashset
Runnable Java Docs: HashSet | Coddy
How do you remove duplicates from a list in Java?
Pass the list to a HashSet constructor: Set unique = new HashSet&lt;&gt;(list);. The set drops repeated values automatically. If you need a list back (and don't mind losing order), wrap it again: new ArrayList&lt;&gt;(unique). Use a LinkedHashSet instead if you want the original order preserved.
🌐
coddy.tech
coddy.tech › docs › hashset
Runnable Java Docs: HashSet | Coddy
🌐
Coderanch
coderanch.com › t › 385915 › java › ride-List-method
How to over ride the List.contains() method. (Java in General forum at Coderanch)
If you use compareTo for checking instead of equals, and a.compareTo(b) == 0 does not imply a.equals(b) for all a and b, then you are breaking the contract for List.contains. That clearly specifies that it should use equals. However, TreeMap and TreeSet possibly violate the contracts for Map and Set since these also use compareTo (or a Comparator).
🌐
Server2client
server2client.com › javacollections › lists.html
Java - Lists in Java and how to use them
The above screenshot shows the ... methods contained within the ArrayList<E> class. A Vector is a resizable-array, ordered implementation of the List<E> interface that permits all elements including null. Vector allows random access to elements and is similar to ArrayList apart from being synchronized. In fact Vector is one of the two original collections shipped with Java, the other ...
🌐
Vultr
docs.vultr.com › java › standard library › java › util › arraylist › containsall()
Java ArrayList containsAll() - Check All Elements Presence
December 3, 2024 - The containsAll() method in Java's ArrayList class is designed to determine if one list contains all elements of another list.
Find elsewhere
🌐
Java Guides
javaguides.net › 2023 › 09 › java-list-contains-example.html
Java List contains() example
September 26, 2023 - The contains() method of the Java List interface is used to determine if a list contains a specified element.
🌐
Coddy.Tech
coddy.tech › docs › hashset
Runnable Java Docs: HashSet | Coddy
June 4, 2026 - When you find yourself calling list.contains(...) inside a loop, that is usually the signal to switch to a set. Sets shine when you combine them. The methods read like plain English once you know which is which: import java.util.HashSet; import java.util.Set; public class Main { public static void main(String[] args) { Set<Integer> a = new HashSet<>(Set.of(1, 2, 3, 4)); Set<Integer> b = new HashSet<>(Set.of(3, 4, 5, 6)); Set<Integer> union = new HashSet<>(a); union.addAll(b); // everything in either set System.out.println(union); // 1 2 3 4 5 6 Set<Integer> intersection = new HashSet<>(a); intersection.retainAll(b); // only what's in both System.out.println(intersection); // 3 4 Set<Integer> difference = new HashSet<>(a); difference.removeAll(b); // in a but not b System.out.println(difference); // 1 2 } }
🌐
Educative
educative.io › answers › what-is-the-arraylistcontainsall-method-in-java
What is the ArrayList.containsAll() method in Java?
The ArrayList.containsAll() method in Java is used to check if the list contains all the elements present in a collection.
🌐
Reddit
reddit.com › r/javahelp › java - list.contains return value
r/javahelp on Reddit: Java - List.contains return value
June 23, 2024 -

java --version
openjdk 17.0.11 2024-04-16
OpenJDK Runtime Environment (build 17.0.11+9-Debian-1deb12u1)
OpenJDK 64-Bit Server VM (build 17.0.11+9-Debian-1deb12u1, mixed mode, sharing)

Hello!

According to OpenJDK ArrayList.contains() returns true if the element is found, however, the following code proves otherwise when passing the the string "123abc и"

-snip

// Holds all the  letters, numbers and symbols from grapheme 
        var localList = new ArrayList<JmeString>();
        localList.addAll(grapheme.getValues());
        this.pout(localList); // prints out all the elements in the list
for(int i = 0; i != phrase.length(); i++){
            if(!localList.contains(phrase.at(i).toString()) ||
               !localList.contains(phrase.at(i).toUpperCase() ){
                super.pout(phrase.at(i) + " is in the array");
                
            }else{
                super.pout(phrase.at(i) + " is not in the array");               
            }
        }

output

[a, e, i, o, u, à, â, ä, æ, è, ê, ë, î, ï, ô, œ, ù, û, ü, á, é, í, ó, ú, b, c, d, f, g, h, j, k, l, m, n, p, q, r, s, t, v, w, x, y, z, ç, ñ, ~, !, @, #, $, %, ^, &, *, (, ), -, _, =, /, +, {, }, [, ], |, ?, ¿, ., , 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

1 is not in the array // is an element of the list

2 is not in the array // is an element of the list

3 is not in the array // is an element of the list

a is not in the array // is an element of the list

b is not in the array // is an element of the list

c is not in the array // is an element of the list

is not in the array //Blank is an element of the list

и is not in the array // This element does not exist in the List

Now the question is:
What am I doing wrong?
Have I misunderstood the algorithm?
or is the OpenJDK 17 page wrong?

Thanks in advance.

🌐
W3Schools
w3schools.com › java › java_list.asp
Java List
The List interface is part of the Java Collections Framework and represents an ordered collection of elements.
🌐
51CTO
blog.51cto.com › u_16175455 › 6754080
Java List contains性能优化指南
July 17, 2023 - The security policy of this website has blocked you from further access. Contact the site owner and provide the Request ID shown on this page · If you are the owner of this website: Refer to the EdgeOne Web Security Analytics documentation for further instructions
🌐
51CTO
blog.51cto.com › u_16213463 › 11404090
java list contains 比较对象中的属性
July 10, 2024 - The security policy of this website has blocked you from further access. Contact the site owner and provide the Request ID shown on this page · If you are the owner of this website: Refer to the EdgeOne Web Security Analytics documentation for further instructions
🌐
Level Up Lunch
leveluplunch.com › java › examples › list-contains-any-elements
List contains any element - Java
January 30, 2014 - @Test public void list_contains_any_java () { // assuming 2013 boolean vehiclesFiveYearOrOlder = false; for (Vehicle vehicle : vehicles) { if ( (vehicle.year - 5) <= 2008) { vehiclesFiveYearOrOlder = true; break; } } assertTrue(vehiclesFiveYearOrOlder); }
🌐
YouTube
youtube.com › cristian ballesteros
Como usar List y ArrayList en JAVA - metodo indexOf lastIndexOf remove contains isEmpty PARTE 1/3 - YouTube
15-Como usar List y ArrayList en JAVA - metodo indexOf lastIndexOf remove contains isEmpty PARTE 1/3
Published: March 22, 2021
Views: 156
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › List.html
List (Java Platform SE 8 )
July 21, 2026 - Returns an iterator over the elements in this list in proper sequence. ... Returns an array containing all of the elements in this list in proper sequence (from first to last element).
🌐
GeeksforGeeks
geeksforgeeks.org › java › list-contains-method-in-java-with-examples
List contains() method in Java with Examples - GeeksforGeeks
December 3, 2024 - The contains() method of List interface in Java is used for checking if the specified element exists in the given list or not.
🌐
W3Schools
w3schools.com › java › ref_arraylist_contains.asp
Java ArrayList contains() Method
The contains() method returns true if an item exists in a list and false otherwise.
🌐
Baeldung
baeldung.com › home › java › java list › check if a list contains a string element while ignoring case
Check if a List Contains a String Element While Ignoring Case | Baeldung
March 7, 2025 - In this quick tutorial, we’ll explore various methods and strategies to solve this common problem in Java. List provides the convenient contains() method to check if a given value exists in the list.