I am practicing the ArrayList with contains method. For checking the objects in the ArrayList, every time I need to loop through the entire ArrayList using for each loop. Therefore, I am thinking if there is a way to do such a check using contains
method.
I've referred to this post: How does a ArrayList's contains() method evaluate objects?
But I am new to java and don't really the meaning of the method. Does it mean to override the equals()
method to check the object? Any help is highly appreciated.
Here is my method trying to check if the user exists in the playerList
.
public void showCertainPlayerInformation(ArrayList<NimPlayer> playerList, String inputName)
{
System.out.println("The request to show the name: "+ inputName);
//trying to use the contains method, but it seems impossible
//if (playerList.contains(NimPlayer.getUserName().equals(inputName)))
for (NimPlayer player : playerList)
{
String userCheck = player.getUserName();
String familyName = player.getFamilyName();
String givenName= player.getGivenName();
int gamesWon = player.getGamesWon();
int gamesPlayed = player.getGamesPlayed();
if (userCheck.equals(inputName))
{
System.out.println(inputName + "," + givenName + ","
+ familyName + "," + gamesPlayed + " games," + gamesWon + " wins");
return;
}
}
System.out.println("The player does not exist");
}