自定义类中2个元素的比较升级到3个元素的比较

可以先参考一下前面的一篇文章: 为了比较,让自己的类实现Comparable接口,重写compareTo

自定义类中2个元素的比较升级到3个元素的比较

在自己定义的类中比较两个


Name.java

package comparable;

class Name implements Comparable<Name> {
	public String firstName, lastName;

	public Name(String firstName, String lastName) {
		this.firstName = firstName;
		this.lastName = lastName;
	}

	public int compareTo(Name o) { // 实现接口
		int lastCmp = lastName.compareTo(o.lastName);
		// 首先比较姓(lastName)如果姓相同(lastCmp==0)再比较名(firstName),否则返回名的比较
		//即是:这一级只要不等就有先后了,如果等,进入下一级比较
		return (lastCmp == 0 ? firstName.compareTo(o.firstName) : lastCmp);
	}

	public String toString() { // 便于输出测试
		return firstName + " " + lastName;
	}
}



NameSort.java

package comparable;

import java.util.*;

public class NameSort {
	public static void main(String[] args) {
		Name[] nameArray = { new Name("John", "Lennon"),
				new Name("Karl", "Marx"), new Name("Groucho", "Marx"),
				new Name("Oscar", "Grouch") };
		Arrays.sort(nameArray);
		for (int i = 0; i < nameArray.length; i++) {
			System.out.println(nameArray[i].toString());
		}
	}
}
输出结果:
Oscar Grouch
John Lennon
Groucho Marx
Karl Marx



在自己定义的类中比较三个


Name.java

package comparable2;

class Name implements Comparable<Name> {
	/*
	 * 相对于包comparable来说,这个在原来前后2个的比较上实现了前中后3个的比较
	 * 最重要的是对compareTo方法的书写
	 * */	
	
	public String firstName, centerName, lastName;

	public Name(String firstName, String centerName, String lastName) {
		this.firstName = firstName;
		this.centerName = centerName;
		this.lastName = lastName;
	}

	public int compareTo(Name o) {
		int firstCmp = firstName.compareTo(o.firstName);
		int centerCmp = centerName.compareTo(o.centerName);
		int lastCmp = lastName.compareTo(o.lastName);
		if (lastCmp == 0) {
			if (centerCmp == 0) {
				return firstCmp;
			} else {
				return centerCmp;
			}
		} else {
			return lastCmp;
		}
	}

	public String toString() { // 便于输出测试
		return firstName + " " + centerName + " " + lastName;
	}
}



NameSort.java

package comparable2;

import java.util.*;

public class NameSort {
	public static void main(String[] args) {
		Name[] nameArray = {  new Name("c", "b", "a"),new Name("a", "b", "a"),
				new Name("c", "a", "b"), new Name("c", "b", "b") };
		Arrays.sort(nameArray);
		for (int i = 0; i < nameArray.length; i++) {
			System.out.println(nameArray[i].toString());
		}
	}
}
输出结果:(注意:按照last->center->first顺序比较)
a b a
c b a
c a b
c b b









.

你可能感兴趣的:(java,C++,c,C#,Blog)