2015-01-12 3 views
1

내 제목은 다음과 같습니다. ArrayList에서 중복 된 이름을 찾아서 방지하고 싶습니다. Set 메서드를 사용할 수 없습니다.중복 된 이름 검색 및 방지 ArrayList

private static void kommandoEtt() { 

    Kund nyKund = new Kund(); 

    System.out.print("Name: "); 

    nyKund.setNamn(tangentbord.nextLine()); 

    kundregister.add(nyKund); 

} 
+0

@ Johan Lundström 귀하의 질문은 매우 명확하지 않습니다, 당신은 뭔가 초보자를 시도해 봤지만, pls는 솔루션을 제공 할 수 있도록 제대로 설명했습니다. –

+0

반복하고 비교하거나 목록에 대한 API 문서를보고 '포함'과 같은 것이 있는지 확인하십시오. –

답변

3

Set을 사용하지 않고, 당신이 List#contains(Object) 방법을 사용하여 List 동일한 두 개체를 추가 피할 수 있습니다 :

여기 내 코드입니다.

예 :

List<String> strings = new ArrayList<String>(); 

if (!list.contains("mystring")) 
    System.out.println("added string? "+list.add("mystring")); 
if (!list.contains("mystring")) 
    System.out.println("added string? "+list.add("mystring")); 

출력 :

added string? true 
added string? false 

함정 방법 위

기본적인 자바 프리미티브 작동 등 String, Double, Integer, ... 등 나만의 물건을 가지고 있다면, hashCode을 덮어 써야합니다. 수업의 방법은 equals입니다. 그렇지 않으면 List#contains 메서드는 콘텐츠가 아닌 개체의 주소를 기반으로 동등성을 테스트합니다.

잘못된 예 :

public class Fraction { 
    int x, int y; 
    public Fraction(int x, int y) { this.x=x;this.y=y;} 
} 

List<Fraction> fractions = new ArrayList<Fraction>(); 
Fraction f1 = new Fraction(1,2); 

if (!fractions.contains(f1)) 
    System.out.println("added fraction? "+fractions.add(f1)); 

if (!fractions.contains(f1)) 
    System.out.println("added fraction? "+fractions.add(f1)); 

출력 :

added fraction? true 
added fraction? true 
고정

예 :

public class Fraction { 
    public int x, int y; 
    public Fraction(int x, int y) { this.x=x;this.y=y;} 
    @Override 
    public boolean equals(Object o) { 
     if (o==null) return false; 
     if (o==this) return true; 
     if (!(o instanceof Fraction) return false; 
     Fraction f = (Fraction) o; 
     return f.x == x && f.y ==y; 
    } 
} 

List<Fraction> fractions = new ArrayList<Fraction>(); 
Fraction f1 = new Fraction(1,2); 

if (!fractions.contains(f1)) 
    System.out.println("added fraction? "+fractions.add(f1)); 

if (!fractions.contains(f1)) 
    System.out.println("added fraction? "+fractions.add(f1)); 

출력 :

added fraction? true 
added fraction? false 
+0

자, 어떻게이 방법을 사용합니까? 어떻게 보이나요? – JLS

0

중복되지 않은 항목을 컨테이너에 추가하는 또 다른 방법은 Set를 사용하는 것입니다. 주문이 동일해야한다면 LinkedHashSet 구현을 사용할 수 있습니다.

그런 다음 클래스에 equals 메소드를 구현하여 항목이 시뮬레이트되었는지 확인해야합니다.

귀하의 경우에는 그 이름이 다른 값일 수 있다고 생각됩니다. 당신은 또한 표준 자바 구현에 의해 조회에 대한 HashSet의 내부의 특정 위치를 얻을 수 있도록 객체의 해시 코드 기능을 구현해야

public boolean equals(Object o) { 

    // if the object you compare to isn't Kund then they aren't equal. 
    if(!(o instanceof Kund)) return false; 

    // return the value of the equals between this object and the object you want  
    // to check equality on. And use the objects name as the field determining if 
    // the values are equal. 
    return this.getName().equalsIgnoreCase((Kund)o.getName()); 
} 

public int hashCode() { 
    return this.getName().hashCode(); 
} 

: 같은 그런 등호가 구현 될 수있다.