2010-12-09 4 views
118

스캐너에 쓰여진 값이 ArrayList에 있는지 확인할 수 있습니까?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(); 

답변

221

그냥 ArrayList.contains(desiredElement)을 사용하십시오. 당신이 당신의 예에서 conta1 계정을 찾는 경우 예를 들어, 같은 것을 사용할 수 있습니다

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

편집 :이 작업을 수행하려면 위해서는, 당신은 제대로을 무시해야한다는equals()hashCode() 방법. 이클립스 IDE를 사용하는 경우, 당신은 먼저 CurrentAccount 개체에 대한 소스 파일을 열고 당신이 값의 존재 여부를 확인하는 경우 Source > Generate hashCode() and equals()...

+7

동일 객체 인 경우를 확인하려면 equals() 메서드를 CurrentAccount에서 재정의해야합니다. – Javi

+1

이 경우 hashcode()도 재정의해야합니다. per hashcode() contract equal 객체는 동일한 해시 코드를 가져야합니다. – zockman

+0

@ zockman 당신이 옳다는 것을 확신합니다. 비록 같지 않다면, 모든 속성이 같은 값을 가지고 있어도 CurrentAccount 객체가 같지 않을 수도 있기 때문에,이 경우에 오버라이드가 더 중요하다고 생각합니다. 하지만 hashcode()를 재정의하는 것에 동의합니다. – Javi

32

더 나은이 HashSetArrayList보다를 사용하는 선택에 의해 생성 된 이러한 방법을 가질 수 있습니다. HashSet에 대한 자바 문서는 말한다 : "This class offers constant time performance for the basic operations (add, remove, contains and size)"

ArrayList.contains() 당신이 찾고있는 인스턴스를 찾기 위해 전체 목록을 반복해야 할 수도 있습니다.

8

안녕하세요. this post에 대한 답변을 여기에서 설명합니다. 목록을 반복 할 필요가 없습니다. 단지 equals 메소드를 덮어 씁니다.

equels 방법 대신 == 업데이트

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

} 
+2

==를 사용하여 문자열 비교 –

+0

== 대신 equals()를 사용하여 문자열을 비교하십시오. this.name.equals (employee .getName())' – Lucky

+0

업데이트 된 답변,이 다음 도움이 upvote 경우 :) –

0

.

Use this function: 
arrayList.contains(value); 

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

어레이 목록에 UserDefined DataType의 객체가 포함되어있는 경우.

How to compare Objects attributes in an ArrayList?

Follow this below Link 

나는이 솔루션이 도움이되기를 바랍니다. 감사합니다

관련 문제