2012-09-11 3 views
-1

주어진 클래스에서 정렬하는 데 문제가 있습니다. 데이터가 정렬되지 않습니다. 여기서는 두 목록의 크기가 같지 않지만 목록에는 list1에있는 키가 있습니다. 키와 값 회원들에게 국지적 인 데이터를 갖는 빈 클래스는 sorted.I가동일하지 않은 크기의 목록에서 정렬하는 문제

public class MyList { 

    public static void main(String[] args) { 
     FP f = new FP(); 
     f.setKey("s"); 
     f.setValue("he"); 
     FP f1 = new FP(); 
     f1.setKey("t"); 
     f1.setValue("she"); 
     List<FP> list = new ArrayList<FP>(); 
     list.add(f); 
     list.add(f1); 
     FP f2 = new FP(); 
     f2.setKey("t"); 
     f2.setValue("he"); 
     FP f3 = new FP(); 
     f3.setKey("s"); 
     f3.setValue("she"); 
     FP f4 = new FP(); 
     f4.setKey("u"); 
     f4.setValue("she"); 
     List<FP> list1 = new ArrayList<FP>(); 
     list1.add(f2); 
     list1.add(f3); 
     list1.add(f4); 
     final Map<FP, Integer> indices = new HashMap<FP, Integer>(); 
     for (int i = 0; i < list.size(); i++) { 
      indices.put(list.get(i), i); 
     } 
     Collections.sort(list1, new Comparator<FP>() { 
      public int compare(FP o1, FP o2) { 
       int index1 = (Integer) (indices.containsKey(o1) ? indices 
         .get(o1) : +1); 
       int index2 = (Integer) (indices.containsKey(o2) ? indices 
         .get(o2) : +1); 
       return index1 - index2; 
      } 

     }); 

     for (int i = 0; i < list1.size(); i++) { 
      System.out.println("the data is" + list1.get(i).getKey()); 
     } 

    } 
} 

답변

3

나는 FP 개체를하지 않았다에 문제가 관련이 추측 목록 마지막에 추가 키를 추가 한 같은 순서로 목록 1을 원하지 못하고있다 (indices.containsKey(o1))이 false를 반환 할 수 있기 때문에 equals()hashCode() 메서드를 재정의 할 수 있습니다.

당신은 컬렉션의 내용으로 객체를 사용하고 equals()을 무시하지 않고 hashCode() 조회가 실패 할 경우, contains() (또는) get(object)처럼 조회 사용하여 전화를 할 싶습니다 때.

예 :

Set<FP> keySet=indices.keySet(); 
Iterator<FP> keySetIter = keySet.iterator(); 
while(keySetIter.hasNext()) 
{ 
FP fpObj = keySetIter.next(); 
//Write your equality condition here. 
} 
+0

공공 메소드의 개요 boolean equals (Object obj) { \t \t // TODO 자동 생성 방법 (OBJ) \t \t 반환 super.equals 스텁; \t} \t @Override \t 공개 INT의 해시 코드() {// \t \t TODO() 메소드 스텁을 \t \t 복귀 super.hashCode를 자동 생성; \t} – pars

+0

나는이 또한 – pars

+0

이긴하지만 메서드가 포함되어있어 오류가 발생했습니다. 내 예제로 explian하십시오. – pars

관련 문제