2017-11-11 14 views
0

여러 속성을 가진 Person 클래스가 있고 Person (예를 들어 연령)의 속성이 오름차순으로 정렬 된 ArrayList가 있다고 가정합니다.Java에서 ArrayList의 요소를 어떻게 정렬합니까?

내가하고 싶은 일은 사람을 ArrayList에 추가하는 것입니다. 추가 된 사람은 목록의 다른 요소와 비교되어 직접 정렬됩니다. 즉, 목록의 모든 요소를 ​​추가하고 목록의 순서를 추가하고 싶지 않습니다.

+0

은이 링크에서보세요 : https://stackoverflow.com/questions/18441846/how-to-sort-an-arraylist-in-java –

+0

'은, Collections.sort()' – Malt

+0

ArrayList를 콜렉션 유형으로 사용하는 것이 중요합니까? –

답변

0

모든 요소가 추가 된 후에 비교기를 사용하여 정렬 할 수 있습니다. 그러나 , 당신이에 관심이없는 때문에 다음 '종류'기술 '모두 추가', 아래의 고려 :

  • 가 인 java.util.ArrayList를 확장하는 사용자 정의의 ArrayList를 작성합니다.
  • 요소를 정렬 된 순서로 삽입하는 삽입 방법을 만듭니다.

    public void insert(Person p) { 
    // loop through all persons 
    for (int i = 0; i < size(); i++) { 
         // if the person you are looking at is younger than p, 
         // go to the next person 
         if (get(i).age < p.age) continue; 
         // if same age, skip to avoid duplicates 
         if (get(i).age == p.age) return; 
         // otherwise, we have found the location to add p 
         add(i, p); 
         return; 
    } 
    // we looked through all of the persons, and they were all 
    // younger than p, so we add p to the end of the list 
    add(p); 
    } 
    
관련 문제