gpt4 book ai didi

java - 如何使用 ArrayList.contain() 来检查 java 中的对象

转载 作者:行者123 更新时间:2023-12-02 16:36:06 24 4
gpt4 key购买 nike

我正在练习 ArrayList with contains 方法。为了检查 ArrayList 中的对象,每次我需要使用 for each 循环遍历整个 ArrayList。因此,我在想是否有办法使用 contains 方法进行此类检查。

我引用了这篇文章:How does a ArrayList's contains() method evaluate objects?

但我是 java 新手,并不太了解该方法的含义。是否意味着重写equals()方法来检查对象?非常感谢任何帮助。

这是我尝试检查用户是否存在于 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");
}

最佳答案

是的。您需要像这样定义您的 NimPlayer 类(如果您只想通过用户名比较两个 NimPlayer 对象)

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);
}
}

现在检查数组列表是否包含:

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");
}

关于java - 如何使用 ArrayList.contain() 来检查 java 中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62718310/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com