2013-10-09 3 views
0

보다 효과적이되도록 ArrayList에서 중복 제거하는이 메서드를 향상시킬 수 있습니다이 메서드는 같은 주소 필드를 가진 목록에서 중복 개체를 제거합니다. 그것은 나를 위해 지금 당장 작동합니다. 하지만 난 내 응용 프로그램을 업그레이 드하고 ArrayLists 더 큰 기대하고있다. (200 개체)어떻게하면 O (n2)

이는 O (N2) 나는 그것을 개선 할 수있는 방법

때문에 나는, 그것은 예를 들어 200 개 기록을 비교 너무 느린 수 있습니다 걱정입니다.

public static ArrayList<Place> removeDuplicates(ArrayList<Place> masterList) { 
    ArrayList<Place> tempList = new ArrayList<Place>(masterList); 
    for (int i = 0; i < tempList.size(); i++) { 
     String address = tempList.get(i).getAddress(); 
     for (int j = 0; j < tempList.size(); j++) { 
      String address2 = tempList.get(j).getAddress(); 
      if (address.equalsIgnoreCase(address2) && i != j) { 
       tempList.remove(tempList.get(j)); 
      } 
     } 

    } 
    return tempList; 
} 

편집

감사 만장일치 답변에 대한 모든. 나는 finasl 질문이있다. 내가 그들을 타고 갈 때 hashcode와 equals 메서드는 어떻게됩니까?

+3

이 반복자없이 ArrayList''에서 항목을 제거하지 마십시오 결과를 인쇄 할 수 있습니다. – Maroun

+3

메트릭을 사용하여 애플리케이션에서 병목 현상이 있음을 입증하기 전에이를 향상시키지 마십시오. (* 물론, @ MarounMaroun의 충고 * 다음을 제외하고). –

답변

0

Place 개체에 대한 equalshashcode을 정의한 경우, 단지의 ArrayList에서 HashSet를 만든 다음 세트에서의 ArrayList를 만들 수 있습니다.

1

가장 좋은 방법은 hashcodeequals 개의 메소드를 덮어 쓰고 목록에서 세트를 생성하는 것입니다.

이렇게하면 목록이 아닌 중복 된 요소를 제거하는 것이 좋습니다.

+0

내가 타고 갈 때 hascode 및 equals 메서드에 어떤 영향을 줍니까? – code511788465541441

+0

Eclipse (Source >> Generate hashcode() and equals() ...) 또는 Nebeans를 사용하여 자동으로 코드를 생성하거나 Effective Java 2를 살펴보십시오. Item 8 : 일반 계약에 복종하십시오 을 오버라이드하고'Item 9 - equals를 오버라이드 할 때 항상 hashCode를 오버라이드 ' – user278064

+0

감사합니다. 주소 필드에 대해서만 생성했습니다. 나는 그것을 시도 할 것이다 – code511788465541441

5

인스턴스 좋은 해시 코드를 생성하고 사용하는지 확인 HashSet 또는 LinkedHashSet (당신은 순서를 유지하려는 경우) : 장소의

return new ArrayList<Place>(new LinkedHashSet<Place>(masterList)); 
+1

+1 주문에 관한 좋은 지적 – mishadoff

1
public static ArrayList<Place> removeDuplicates(ArrayList<Place> masterList) { 
    Set<Place> temp = new HashSet<Place>(); 
    for(Place place : masterList) { 
     if(!temp.add(place)) { 
      masterList.remove(place); 
     } 
    } 

    return masterList; 
} 
+0

동일한 주소 영역을 가지고 있어도 객체가 같지 않을 수도있다. – code511788465541441

+0

정의 된 'equals' 메쏘드를 사용하면 객체를 동일하게 선언 할 때 스스로를 결정해야한다. –

1

귀하의 masterlist

List<Place> masterList = new ArrayList<Place>(); 
    masterList.add(new Place()); 
    masterList.add(new Place()); 
    masterList.add(new Place()); 

을 중복 제거 "s"를 추가하여 추가

Set<Place> s = new TreeSet<Place>(new Comparator<Place>() { 
     @Override 
     public int compare(Place o1, Place o2) {     
      return o1.getAddress().compareToIgnoreCase(o2.getAddress());     
     }   
    }); 

    s.addAll(masterList); 

List<Object> res = Arrays.asList(s.toArray()); 
    for (Object object : res) { 
     Place place = (Place)object; 

    } 
관련 문제