Java静态内部类实例
package com.swsx.sort; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class TestComparator { public static void main(String[] args){ Student std1 = new Student(1,"bb"); Student std2 = new Student(2,"aa"); Student std3 = new Student(3,"dd"); Student std4 = new Student(4,"cc"); List<Student> students = new ArrayList<Student>(); students.add(std3); students.add(std4); students.add(std1); students.add(std2); //按id排序 Collections.sort(students, new Student.ById()); System.out.println(students); //按name排序 Collections.sort(students, new Student.ByName()); System.out.println(students); } /** * 学生类 * 静态内部类 外围类相当于一个命名空间 * @author Administrator * */ public static class Student{ private int id; private String name; public Student(int id, String name) { super(); this.id = id; this.name = name; } /** * 按id排序 * 静态内部类 不需要外围类实例化 * @author Administrator * */ public static class ById implements Comparator<Student>{ @Override public int compare(Student o1, Student o2) { // TODO Auto-generated method stub return o1.id == o2.id ? 0:o1.id < o2.id ? -1:1; } } /** * 按name排序 * @author Administrator * */ public static class ByName implements Comparator<Student>{ @Override public int compare(Student o1, Student o2) { // TODO Auto-generated method stub return o1.name.compareTo(o2.name); } } @Override public String toString() { return "student [id=" + id + ", name=" + name + "]"; } } } /*输出: [student [id=1, name=bb], student [id=2, name=aa], student [id=3, name=dd], student [id=4, name=cc]] [student [id=2, name=aa], student [id=1, name=bb], student [id=4, name=cc], student [id=3, name=dd]] */
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。