Java中实现对象的比较

Java中通过接口实现两个对象的比较,首先类要实现comparable接口,使用泛型规定了要进行比较的对象所属的类,而comparable接口的实现必须要定义的方法则是compareTo方法,在方法中传入此类的另一个对象,通过选定的成员变量与之比较,如果大于则返回1,小于返回-1,相等返回0.

例子代码:

package com.study.write;
import java.util.*;

public class EmployeeSortTest {
	public static void main(String[] args) {
		Employee2[] staff = new Employee2[3];
		staff[0] = new Employee2("Harry", 35000);
		staff[1] = new Employee2("Danny", 40000);
		staff[2] = new Employee2("Tony", 20000);
		
		Arrays.sort(staff);
		
		//print out information about all Employee objects
		for(Employee2 e:staff)
			System.out.println("name = " + e.getName() +" " + "salary = " + e.getSalary());
	}

}

class Employee2 implements Comparable<Employee2> {
	public Employee2(String n, double s) {
		name = n;
		salary = s;
	}
	
	public String getName() {
		return name;
	}
	
	public double getSalary() {
		return salary;
	}
	
	public void raiseSalary(double byPecent) {
		double raise = salary * byPecent / 100;
		salary += raise;
	}
	
	/**compares employees by salary
	 @param other another Employee object
	 @return a negative value if this employee has a lower
	 salary than otherObject, 0 if the salaries are the same,
	 a positive value otherwise
	 */
	public int compareTo(Employee2 other) {
		if(salary < other.salary) return -1;
		if(salary > other.salary) return 1;
		return 0;
	}
	
	private String name;
	private double salary;
}


 

运行结果为:
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值