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]]
 */

Java静态内部类实例,布布扣,bubuko.com

Java静态内部类实例

上一篇:字符串类 java


下一篇:spring IoC源码分析 (3)Resource解析