How does a ArrayList's contains() method evaluate objects?
ArrayList implements
the List Interface.
If you look at the Javadoc for List
at the contains
method you will see that it uses the equals()
method to evaluate if two objects are the same.
How to use the ArrayList.contain() to check the object in java
Yes. You need to define your NimPlayer class like this (if you want to compare two NimPlayer objects only by their userName)
package com.example.schooltimetable;
import java.util.Objects;
public class NimPlayer {
private String userName;
private String familyName;
private String givenName;
private int gamesWon;
private int gamesPlayed;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getFamilyName() {
return familyName;
}
public void setFamilyName(String familyName) {
this.familyName = familyName;
}
public String getGivenName() {
return givenName;
}
public void setGivenName(String givenName) {
this.givenName = givenName;
}
public int getGamesWon() {
return gamesWon;
}
public void setGamesWon(int gamesWon) {
this.gamesWon = gamesWon;
}
public int getGamesPlayed() {
return gamesPlayed;
}
public void setGamesPlayed(int gamesPlayed) {
this.gamesPlayed = gamesPlayed;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
NimPlayer nimPlayer = (NimPlayer) o;
return Objects.equals(userName, nimPlayer.userName);
}
@Override
public int hashCode() {
return Objects.hash(userName);
}
}
Now to check if the arraylist contains :
public void showCertainPlayerInformation(ArrayList<NimPlayer> playerList, String inputName)
{
NimPlayer n = new NimPlayer();
n.setUserName(inputName);
if(playerList.contains(n)){
....
return;
}
System.out.println("The player does not exist");
}
How to look up for exact same objects with .contains() method in java?
Override equals
(& hashCode
)
You neglected to provide overrides of the inherited Object#equals
and Object#hashCode
methods.
The default implementation of equals
uses identity to compare, that is, "Do the two object references being compared share the same implicit memory address?".
Instead, you want to compare the contents of the two objects. So you need to write that content-comparison code in your own equals
method. And whenever overriding equals
, it is generally best to override hashCode
using the same logic.
Your IDE will assist you in writing that code. For example, in IntelliJ, see this documentation and this discussion.
This issue has been covered many times on Stack Overflow. So search to learn more.
Records
By the way, you can more briefly define your class as a record.
record Archive ( String identifier , String name ) {}
A record is appropriate when the main purpose of your class is to communicate data transparently and immutably.
The compiler implicitly creates the constructor, getters, equals
& hashCode
, and toString
methods.
So using a record makes your problem moot, assuming you want to compare each and every member field on the class. The equals
& hashCode
overrides are provided for you.
Evaluating objects containing Strings with Java ArrayList contains()
java.util.ArrayList#indexOf
is used internally in ArrayList for contains()
.
There is a check,
o.equals(elementData[i])
So there is comparison of string with your object, so String.equals()
is invoked for check of equality.
How to find object in arraylist with the Contains method
You are comparing an Account with an AccountNumber. Instead of this, you should do this.
public boolean checkAccountNumber(int a) {
for (Account account of Bank.accounts){
if (account.accNumber.equals(a)) {
return true;
}
}
return false;
}
Java ArrayList contains method does not identify integer data type
Lists are generic classes. See Tutorial by Oracle.
So when you do the following:
List<Object> list = new ArrayList<>();
list.add(2L);
The 2L
boxes as a Long
, whereas 2
boxes as an Integer
.
So list.contains(2)
looks for an Integer
and thus won't find your 2L
entry.
Does the ArrayList's contains() method work faster if the ArrayList is ordered?
Does the ArrayList's contains() method work faster if the ArrayList is ordered?
It doesn't. The implementation of ArrayList
does not know if the list is ordered or not. Since it doesn't know, it cannot optimize in the case when it is ordered. (And an examination of the source code bears this out.)
Could a (hypothetical) array-based-list implementation know? I think "No" for the following reasons:
Without either a
Comparator
or a requirement that elements implementComparable
, the concept of ordering is ill-defined.The cost of checking that a list is ordered is
O(N)
. The cost of incrementally checking that a list is still ordered isO(1)
... but still one or two calls tocompare
on each update operation. That is a significant overhead ... for a general purpose data structure to incur in the hope of optimizing (just) one operation in the API.
But that's OK. If you (the programmer) are able to ensure (ideally by efficient algorithmic means) that a list is always ordered, then you can use Collections.binarySearch
... with zero additional checking overhead in update operations.
Java - contains check all items in an arraylist meet a condition
Iterate and use contains. Remove the or conditions if you want case specific.
public static boolean isListContainMethod(List<String> arraylist) {
for (String str : arraylist) {
if (!str.toLowerCase().contains("method")) {
return false;
}
}
return true;
}
ArrayList's contains() method always returns false with custom object
Your equals
implementation is incorrect. equals
has a specific contract; that code attempts to violate that contract. From the documentation:
The equals method implements an equivalence relation on non-null object references:
- It is reflexive: for any non-
null
reference valuex
,x.equals(x)
should returntrue
.- It is symmetric: for any non-
null
reference valuesx
andy
,x.equals(y)
should returntrue
if and only ify.equals(x)
returnstrue
.- It is transitive: for any non-
null
reference valuesx
,y
, andz
, ifx.equals(y)
returnstrue
andy.equals(z)
returnstrue
, thenx.equals(z)
should returntrue
.- It is consistent: for any non-
null
reference valuesx
andy
, multiple invocations ofx.equals(y)
consistently returntrue
or consistently returnfalse
, provided no information used inequals
comparisons on the objects is modified.- For any non-
null
reference valuex
,x.equals(null)
should returnfalse
.
There's no way to make an instance of your Sign
class equals
to a string.
Related Topics
Under What Conditions Is a Jsessionid Created
Java Maximum Memory on Windows Xp
How to Set the Default Locale in the Jvm
Sorting a Collection of Objects
Nosuchelementexception with Java.Util.Scanner
Moving Decimal Places Over in a Double
Getting the 'External' Ip Address in Java
.Toarray(New Myclass[0]) or .Toarray(New Myclass[Mylist.Size()])
Convert Java.Util.Date to Java.Time.Localdate
How to Iterate Through the Files in a Directory and It's Sub-Directories in Java
How to Import a Class from Default Package
How to Get the Exact Middle of a Screen, Even When Re-Sized