머리말
java.util 패키지의 목록 인터페이스는 컬렉션 인터페이스를 상속하고 객체 컬렉션을 저장하는 데 사용됩니다. 따라서 이러한 객체를 정렬 할 때 객체 클래스는 동일한 객체 자체를 비교하거나 비교기를 사용하여 비교 및 정렬을 수행 할 수 있습니다.
이름 및 연령 속성을 포함한 학생 엔티티 클래스는 비교할 때 이름으로 오름차순 순서로 정렬되며 이름이 동일하면 연령의 오름차순 순서로 정렬됩니다.
첫 번째 유형 : 자체적으로 엔티티 클래스 비교
(비슷한 인터페이스 구현 : public interface Comparable<T> , 메소드 선언이 있습니다 : public int compareTo(T o); )
샘플 코드 :
공개 클래스 학생은 비슷한 <tudly> {개인 문자열 이름을 구현합니다. 사적인 int 연령; 공개 학생 () {super (); // TODO 자동 생성 생성자 Stub} 공개 학생 (문자열 이름, int age) {super (); this.name = 이름; this.age = age; } public String getName () {return name; } public void setName (문자열 이름) {this.name = 이름; } public int getage () {반환 연령; } public void 설정 (int Age) {this.age = age; } @override public int compareto (student o) {// todo 자동 생성 메소드 Stub int flag = this.name.compareto (o.name); if (flag == 0) {flag = this.age -O.age; } 반환 플래그; }} 그런 다음 목록 클래스의 sort(Comparator<? super E> c) 메소드를 사용하여 java.util.Collections 도구 클래스의 sort(List<T> list) 사용하십시오 (실제로는 하나의 문장 만 있습니다 : list.sort(null); ).
목록 <tudent> 학생 = New ArrayList <tudent> (); 학생 .add (신입생 ( "A", 10)); 학생 .add (신입생 ( "B", 12)); 학생 .add (신입생 ( "B", 11)); 학생 .add (신입생 ( "AC", 20)); 학생들 (null); //collections.sort(students);
결과:
A 10 AC 20 B 11 B 12
두 번째 유형 : 비교기의 도움으로 정렬하십시오.
샘플 코드 :
공개 클래스 학생 {개인 문자열 이름; 사적인 int 연령; 공개 학생 () {super (); // TODO 자동 생성 생성자 Stub} 공개 학생 (문자열 이름, int age) {super (); this.name = 이름; this.age = age; } public String getName () {return name; } public void setName (문자열 이름) {this.name = 이름; } public int getage () {반환 연령; } public void 설정 (int Age) {this.age = age; }} 비교기 java.util.Comparator 클래스는 인터페이스 ( public interface Comparator<T> )이며 int compare(T o1, T o2); 및 기타 방법 :
비교기는이 인터페이스를 구현하고 compare 방법을 구현하려고합니다.
Private Class Student Comparator는 비교기 <guldent> {@override public int 비교 (학생 O1, Student O2) {// todo 자동 생성 메소드 Stub int flag = o1.getName (). compareto (o2.getName ()); if (flag == 0) {flag = o1.getage () - o2.getage (); } 반환 플래그; }} 비교할 때, 목록의 sort(Comparator<? super E> c) 목록 (또는 정렬 ( sort(List<T> list, Comparator<? super T> c) 메소드 java.util.Collections 사용할 수 있습니다.
목록 <tudent> 학생 = New ArrayList <tudent> (); 학생 .add (신입생 ( "A", 10)); 학생 .add (신입생 ( "B", 12)); 학생 .add (신입생 ( "B", 11)); 학생 .add (신입생 ( "AC", 20)); test t = new test (); 학생 .SORT (T.New StudentComparator ()); //collections.sort(students, t.new student comparator ()); for (학생 학생 : 학생) {System.out.println (Student.getName ()+""+Student.getage ()); } 결과는 첫 번째 방법과 동일합니다.
A 10 AC 20 B 11 B 12
요약
위의 것은 Java의 목록을 정렬하는 것에 관한 것입니다. 이 기사의 내용이 모든 사람의 연구 나 업무에 도움이되기를 바랍니다. 궁금한 점이 있으면 의사 소통을 위해 메시지를 남길 수 있습니다.