2010-01-20 3 views
2

알파벳순 또는 숫자순으로 ArrayList을 어떻게 분류합니까? 어떻게 알파벳순으로 또는 숫자로 배열을 정렬하는 방법이 효과가 있을지 모르겠습니다.배열 목록 정렬

감사합니다.

+0

Collections.sort를 호출 할 수 있습니다. 제발 좀 더 자세히 설명해주세요. 사례를 통해 문제 설명 –

답변

2

[Collections.sort] [1] 기본적으로 정렬 순서대로 정렬됩니다. 문자열의 경우 어휘 (알파벳순)이고 숫자 데이터 유형의 경우 숫자입니다. 비표준 주문이 필요한 경우 자체 비교기를 지정할 수도 있습니다.

ArrayList list = new ArrayList(); 
list.add(1); 
list.add(10); 
list.add(-1); 
list.add(5); 

Collections.sort(list); 

[1] : 예

http://java.sun.com/javase/6/docs/api/java/util/Collections.html#sort(java.util.List, java.util.Comparator)

+1

어떻게 그런 정렬 메커니즘을 구현 할지를 묻는 중일 수도 있지만 일반적으로 비즈니스 세계에서 원하는 것은 아닙니다. 숙제 인 경우이를 숙지하고보다 구체적인 것으로 태그를 지정하십시오. –

3

Collections.sort 방법들이 특정 분류 방식을 구현하는 Comparator으로 목록을 정렬을 허용 (예를 들어 알파벳 또는 숫자 정렬).

0
Collections.sort(list,new Comparator() { 

    int compare(T o1, T o2) { 
     // implement your own logic here 
    } 


    boolean equals(Object obj) { 
     // implement your own logic here 
    } 
} 
1

일반적 간단한 배열리스트를 정렬하는 방법을 사용 Collections.sort().

다음은 예입니다.

먼저 Comparable 인터페이스를 구현 한 다음 compareTo 메서드를 재정의합니다.

public class Student implements Comparable { 
    private String studentname; 
    private int rollno; 
    private int studentage; 

    public Student(int rollno, String studentname, int studentage) { 
     this.rollno = rollno; 
     this.studentname = studentname; 
     this.studentage = studentage; 
    } 

    @Override 
    public int compareTo(Student comparestu) { 
     int compareage=((Student)comparestu).getStudentage(); 
    } 

    @Override 
    public String toString() { 
     return "[ rollno=" + rollno + ", name=" + studentname + ", age=" + studentage + "]"; 
    } 

} 

이제 우리는 아주 잘 그것은 전혀 분명 당신이 찾고되지 않는 것을 ArrayList를

import java.util.*; 
public class ArrayListSorting { 

    public static void main(String args[]){ 
     ArrayList<Student> arraylist = new ArrayList<Student>(); 
     arraylist.add(new Student(100, "Nuwan", 19)); 
     arraylist.add(new Student(200, "Kamal", 18)); 
     arraylist.add(new Student(205, "Sunil", 20)); 

     Collections.sort(arraylist); 

     for(Student str: arraylist){ 
      System.out.println(str); 
     } 
    } 
}