码迷,mamicode.com
首页 > 编程语言 > 详细

Java 模拟 Comparable接口

时间:2015-06-18 13:22:03      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:

一、情况

1.目标:要在专门用于排序数据的DataSorter.java中实现对所有A类,B类,C类,D类等等的排序

2.初步想法:DataSorter.java的代码如下

 

public class DataSorter {

	public static void sort(A a){
		
	}
	
	public static void sort(B a){
		
	}
	
	public static void sort(C c){
		
	}
	
	//...................
}

 

  

3.这样会造成DataSorter的可扩展性差,要支持对新类的排序时,要修改代码。更好的思路是:既然DataSorter是要根据不同的类的采取不同的方法实现排序,那么具体实现排序的方法交由子类去实现,且都实现同一个接口Comparable,那么DataSorter只需对Comparable排序,而无需理会具体要排序的是什么类(多态)

4.有如下几个类:

(1)DataSorter.java

(2)接口Comparable.java

(3)Student.java

(4)Teacher.java

(5)Test.java

技术分享

 

 

5.代码如下:

(1)DataSorter.java

public class DataSorter {

	public static void sort(Comparable [] a) {
		
		int index;							//保存每次比较,最大值的下标;
		
		for(int i = 1; i < a.length; i++){	//控制外循环次数
			index = 0;
			for(int j = 1; j <= a.length - i ; j++){
				if(a[j].compareTo(a[index]) == 1){
					index = j;
				}
			}
			swap(a, index, a.length -i);
		}
	}


	private static void swap(Comparable[] a, int x, int y) {
		Comparable tmp = a[x];
		a[x] = a[y];
		a[y] = tmp;
		
	}
	
	
	//输出数组元素
	public static void show(Comparable[] a) {
		for(int i = 0; i < a.length; i++){
			System.out.println(a[i]);
		}
	}

}

  

(2)Comparable.java

public interface Comparable<T> {
	public int compareTo(T o);
}

  

(3)Teacher.java

public class Teacher implements Comparable<Teacher> {

	private int title;
	
	public Teacher(int title) {
		super();
		this.title = title;
	}

	public int getTitle() {
		return title;
	}

	public void setTitle(int title) {
		this.title = title;
	}

	@Override
	public int compareTo(Teacher o) {
		if(this.title > o.getTitle()){
			return 1;
		}else if(this.title == o.getTitle()){
			return 0;
		}else{
			return -1;
		}
	}
	
	@Override
	public String toString() {
		return "teacher--" +title+" ";
	}
}

  

(4)Student.java

public class Student implements Comparable<Student> {

	private int mark;

	public int getMark() {
		return mark;
	}

	public void setMark(int mark) {
		this.mark = mark;
	}

	public Student(int mark) {
		super();
		this.mark = mark;
	}
	
	@Override
	public String toString() {
		return "student" +mark+" ";
	}

	@Override
	public int compareTo(Student o) {
		if(this.mark > o.getMark()){
			return 1;
		}else if(this.mark == o.getMark()){
			return 0;
		}else{
			return -1;
		}
	}
}

  

(5)Test.java

public class Test {

	public static void main(String[] args) {
		//int [] a = {9,2,1,8,0,3};
		Student [] ss = {new Student(59),new Student(30),new Student(90)};
		DataSorter.sort(ss);
		DataSorter.show(ss);
		
		Teacher [] ts = {new Teacher(10),new Teacher(3),new Teacher(12)};
		DataSorter.sort(ts);
		DataSorter.show(ts);
		
	}

}

  

测试结果

技术分享

Java 模拟 Comparable接口

标签:

原文地址:http://www.cnblogs.com/shamgod/p/4585488.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!