检查ArrayList中是否存在值

时间:2010-12-09 23:11:52

标签: java arraylist contains

如何检查ArrayList中写入的值是否存在?

List<CurrentAccount> lista = new ArrayList<CurrentAccount>();

CurrentAccount conta1 = new CurrentAccount("Alberto Carlos", 1052);
CurrentAccount conta2 = new CurrentAccount("Pedro Fonseca", 30);
CurrentAccount conta3 = new CurrentAccount("Ricardo Vitor", 1534);
CurrentAccount conta4 = new CurrentAccount("João Lopes", 3135);

lista.add(conta1);
lista.add(conta2);
lista.add(conta3);
lista.add(conta4);

Collections.sort(lista);

System.out.printf("Bank Accounts:" + "%n");
Iterator<CurrentAccount> itr = lista.iterator();
while (itr.hasNext()) {
    CurrentAccount element = itr.next();
    System.out.printf(element + " " + "%n");
}
System.out.println();

8 个答案:

答案 0 :(得分:282)

只需使用ArrayList.contains(desiredElement)即可。例如,如果您正在寻找示例中的conta1帐户,则可以使用以下内容:

if (lista.contains(conta1)) {
    System.out.println("Account found");
} else {
    System.out.println("Account not found");
}

修改 请注意,为了使其正常工作,您需要正确覆盖equals()hashCode()方法。如果您正在使用Eclipse IDE,那么您可以通过首先打开CurrentAccount对象的源文件并选择Source > Generate hashCode() and equals()...

来生成这些方法。

答案 1 :(得分:42)

在检查是否存在值时,最好使用HashSet而不是ArrayListHashSet的Java文档说:"This class offers constant time performance for the basic operations (add, remove, contains and size)"

ArrayList.contains()可能必须迭代整个列表才能找到您要查找的实例。

答案 2 :(得分:15)

请参阅this post上的答案。

无需迭代List只是覆盖equals方法。

使用equals代替==

@Override
public boolean equals (Object object) {
    boolean result = false;
    if (object == null || object.getClass() != getClass()) {
        result = false;
    } else {
        EmployeeModel employee = (EmployeeModel) object;
        if (this.name.equals(employee.getName()) && this.designation.equals(employee.getDesignation())   && this.age == employee.getAge()) {
            result = true;
        }
    }
    return result;
}

这样称呼:

public static void main(String args[]) {

    EmployeeModel first = new EmployeeModel("Sameer", "Developer", 25);
    EmployeeModel second = new EmployeeModel("Jon", "Manager", 30);
    EmployeeModel third = new EmployeeModel("Priyanka", "Tester", 24);

    List<EmployeeModel> employeeList = new ArrayList<EmployeeModel>();
    employeeList.add(first);
    employeeList.add(second);
    employeeList.add(third);

    EmployeeModel checkUserOne = new EmployeeModel("Sameer", "Developer", 25);
    System.out.println("Check checkUserOne is in list or not");
    System.out.println("Is checkUserOne Preasent = ? " + employeeList.contains(checkUserOne));

    EmployeeModel checkUserTwo = new EmployeeModel("Tim", "Tester", 24);
    System.out.println("Check checkUserTwo is in list or not");
    System.out.println("Is checkUserTwo Preasent = ? " + employeeList.contains(checkUserTwo));

}

答案 3 :(得分:5)

如果我们提供了containsequals的实现,则可以使用hashCode方法检查是否存在某项,否则将使用对象引用进行相等性比较。同样在列表contains的情况下,O(n)O(1)的{​​{1}}操作,因此以后使用时更好。在Java 8中,我们还可以使用流根据项目的相等性或特定属性来检查项目。

Java 8

HashSet

答案 4 :(得分:1)

public static void linktest()
{
    System.setProperty("webdriver.chrome.driver","C://Users//WDSI//Downloads/chromedriver.exe");
    driver=new ChromeDriver();
    driver.manage().window().maximize();
    driver.get("http://toolsqa.wpengine.com/");
    //List<WebElement> allLinkElements=(List<WebElement>) driver.findElement(By.xpath("//a"));
    //int linkcount=allLinkElements.size();
    //System.out.println(linkcount);
    List<WebElement> link = driver.findElements(By.tagName("a"));
    String data="HOME";
    int linkcount=link.size();
    System.out.println(linkcount);
    for(int i=0;i<link.size();i++) { 
        if(link.get(i).getText().contains(data)) {
            System.out.println("true");         
        }
    } 
}

答案 5 :(得分:1)

只需使用.contains即可。例如,如果您正在检查ArrayList arr是否包含值val,那么您只需运行arr.contains(val),它将返回一个表示该值是否包含的布尔值。有关详细信息,请参阅.contains的{​​{3}}。

答案 6 :(得分:0)

当Array List包含Primitive DataType的对象时。

Use this function:
arrayList.contains(value);

if list contains that value then it will return true else false.

当Array List包含UserDefined DataType的对象时。

Follow this below Link 

How to compare Objects attributes in an ArrayList?

我希望这个解决方案可以帮到你。 感谢

答案 7 :(得分:0)

下面的代码可以帮助

List<CurrentAccount> lista = new ArrayList<CurrentAccount>();
CurrentAccount conta5 = new CurrentAccount("Pedro Fonseca", 500);
boolean isAdded = lista.contains(model);
<块引用>

ArrayList 已经有相同的名字,所以它返回 true

import com.google.gson.annotations.SerializedName;    
import java.util.Objects;

public class CurrentAccount {

    @SerializedName("Name")
    private String name;
    
    @SerializedName("Balance")
    private int balance;


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getBalance() {
        return balance;
    }

    public void setBalance(int balance) {
        this.balance = balance;
    }

    public CurrentAccount(String name, int balance) {
        this.name = name;
        this.balance = balance;
    }
    
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        CurrentAccount model = (CurrentAccount) o;
        return name.equals(model.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name);
    }
}