`
yangyangmyself
  • 浏览: 229908 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

Comparable interface

    博客分类:
  • Java
阅读更多
     如果要比较两个对象则Comparable接口很实用,虽然还有另一个接口Comparator,但我们现在只介绍接口Comparable用法。比较两个对象先要实现接口Comparable,并且实现compareTo方法,建议compareTo与equals比较规则一样。compareTo方法定义,查看API文档(文档已详细说明),实例结合java.util.Arrays.sort()方法。下面提供实例说明:
package cn.lang;

/**
 * <li>当且仅当 e1.compareTo(e2) == 0 与 e1.equals(e2) 具有相同的 boolean 值时,类 C 的自然排序才叫做与 equals 一致
 * null 不是任何类的实例,即使 e.equals(null) 返回 false,e.compareTo(null) 也将抛出 NullPointerException。</li>
 * <li>建议(虽然不是必需的)最好使自然排序与 equals 一致。这是因为在使用自然排序与 equals 不一致的元素(或键)时,
 * 没有显式比较器的有序集合(和有序映射表)行为表现“怪异”。尤其是,这样的有序集合(或有序映射表)
 * 违背了根据 equals 方法定义的集合(或映射表)的常规协定。</li>
 * <li>实际上,所有实现 Comparable 的 Java 核心类都具有与 equals 一致的自然排序。
 * java.math.BigDecimal 是个例外,它的自然排序将值相等但精确度不同的 BigDecimal 对象(比如 4.0 和 4.00)视为相等。</li>
 * @author Administrator
 * @since 2011-12-26
 *
 */
class Person implements Comparable<Person>{
	
	private String name;
	private int age ;
	private String school ;
	
	public Person(String name,int age,String school){
		this.name = name ;
		this.age = age ;
		this.school = school ;
	}
	@Override
	public int compareTo(Person t){
		try{
			if(t==null) throw new Exception("对象不能为空!");
		}catch(Exception e){
			System.out.println(this.getClass().getName()+"异常信息:"+e.getMessage());
		}
		if(this.age>t.age){
			return -1 ;
		}else if(this.age<t.age){
			return 1;
		}else{
			return 0 ;
		}
	}
	@Override
	public boolean equals(Object o){
		if(this == o) return true;
		if(!(o instanceof Person)) return false;
		Person p = (Person)o ;
		if(this.age==p.age){
			return true;
		}else{
			return false;
		}
	}
	@Override
	public String toString(){
		return "姓名:"+this.name+"、年龄:"+this.age+"、学校:"+this.school ;
	}
}
public class ComparableDemo01{
	/**
	 * 测试
	 * @param args
	 */
	public static void main(String[] args) {
		Person p1 = new Person("张三",10,"学校一");
		Person p2 = new Person("李四",15,"学校二");
		Person p3 = new Person("王五",8,"学校三");
		Person p4 = new Person("小李",6,"学校四");
		Person p5 = new Person("小二",16,"学校五");
		Person p[] = {p1,p2,p3,p4,p5};
		System.out.println("排序前:");
		for(Person person:p){
			System.out.println(person);
		}
		java.util.Arrays.sort(p);
		System.out.println("排序后:");
		for(Person person:p){
			System.out.println(person);
		}
	}
}



package com.yy.basic;

import java.util.Set;
import java.util.TreeSet;

public class Student implements Comparable<Student>{
	
	private int id ;
	
	private String name ;
	
	private String school ;
	
	public Student(int id, String name, String school){
		this.id = id ;
		this.name = name ; 
		this.school = school ;
	}
	
	@Override
	public int compareTo(Student o) {
		int result = 0;
		result = id > o.id ? 1 : (id == o.id ? 0 : -1);
		if(result==0){
			result = name.compareTo(o.name);
		}
		return result ;
	}
	
	@Override
	public boolean equals(Object obj) {
		if(this == obj){
			return true ;
		}
		if(obj instanceof Student){
			Student student = (Student) obj;
			if(this.id == student.id && this.name.equals(student.name) ){
				return true ;
			}
		}
		return false;
	}
	
	@Override
	public int hashCode() {
		return id + this.name.hashCode();
	}

	@Override
	public String toString() {
		
		return this.id + "_" + this.name + "_" + this.school;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getSchool() {
		return school;
	}

	public void setSchool(String school) {
		this.school = school;
	}
	public static void main(String[] args) {
		Set<Student> set = new TreeSet<Student>();
		set.add(new Student(1,"oy","zh"));
		set.add(new Student(2,"oy","zh"));
		set.add(new Student(1,"o1","zh"));
		set.add(new Student(4,"oy","zh"));
		set.add(new Student(3,"oy","zh"));
		System.out.println(set);
	}
}

分享到:
评论

相关推荐

    interfaceComparable

    interfaceComparable

    深入理解Java之接口

     public interface Comparable&lt;T&gt; {  int compareTo(T o);  }  Comparable接口中定义了一个compareTo方法,这个方法是它所描述的需求。若我们想调用Arrays.sort方法对一个People对象数组进行比较,那么...

    Java容器.xmind

    实现comparable接口,元素是以二叉树的形式存放的。线程不安全 CopyOnWriteArraySet 标记: class Queue 标记: interface BlockingQueue 标记: interface ArrayBlockingQueue LinkedBlockingQueue ...

    Java-basics-recap:坚实的基础使进步变得容易,可以实现更高的目标

    那么我将执行服务” 如果元素类符合Comparable接口,则Arrays.sort对数组进行排序接口定义: public interface Comparable &lt;T&gt;{ int compareTo ( T other );} 一致性类必须提供compareTo方法如果您的课程不符合...

    TemplateDPMerge:模板设计模式和归并排序算法的实现

    所有序列都包含实现 Comparable 接口的对象。 public interface Sequence&lt;T&gt; extends Iterable&lt;T&gt; { // Adds the element t at the rear of the sequence. public void add(T t); // The objects from s are...

    Java-学习Map复习总结

    Map双边队列 1. 什么是Map? 1.1 Map双边队列的概念: Map是一种以键(key)值(value)...需要为key提供对应的比较方式(如果添加的元素没有自然顺序的话)(Comparable或者Comparator)。 关于Comparator比较器的使用: pu

    Java8Utility

    @FunctionalInterface:虽然是可选的 接口仅包含一个抽象函数 他们只能展示一种功能 Lambda表达式可用于表示功能接口的实例 Runnable,ActionListener,Comparable是功能性接口的一些示例 可以包含默认和静态方法 ...

    Expert One-on-One J2EE Design and Development

    In this book, you will learn When to use a distributed architecture When and how to use EJB How to develop an efficient data access strategy How to design a clean and maintainable web interface How ...

    java8stream源码-java8:Java8特性

    java8流源码Java 8 Java 8 特性以及如何使用新特性。 java 8 对可怜的眼睛来说是不是不那么痛苦了.......Runnable、Callable、...@FunctionalInterface,如果没有维护合约,编译器会抱怨。 在 Java 8 中,java.util.f

    通用实践第二:通用第二实践

    public interface Comparable &lt;T&gt; { int compareTo ( T o ); } Содержитодинметод compareTo() ,которыйнеобходимобудетреализоватьвклассе。 Пр...

    【05-面向对象(下)】

    •和类定义不同,定义接口不再用class关键字,而是使用interface关键字。语法如下: •[修饰符] interface接口名 extends 父接口1,父接口2 ... •{ • 零个到多个常量定义... • 零个到多个抽象方法定义... • ...

    FastReport.v4.9.81 for.Delphi.BCB.Full.Source企业版含ClientServer中文修正版

    FastReport adds fewer Kb to your application than any other reporting tool with comparable features; FastReport doesn't use any additional DLLs, and can be compiled into your application. Powerful ...

    NewSID(光学习一下代码就可以了,没看清楚介绍别运行)

    Because the installation is skipped, and because disk sector copying is more efficient than file copying, a cloned-based rollout can save dozens of hours over a comparable sysdiff install. In ...

    Report machine 2.4

    comparable with in QuickReport,ReportBuilder. It written on 100% Object Pascal and can be installed in Delphi 2/3/4/5/6 and C++Builder 1/3/4/5/6. 特点 ---- 复杂的报表?在report machine面前,...

    Java学习笔记-个人整理的

    {2.13}\ttfamily interface}{64}{section.2.13} {2.14}JavaBean规范}{66}{section.2.14} {3}常用类}{67}{chapter.3} {3.1}Object类}{67}{section.3.1} {3.1.1}\ttfamily toString}{67}{subsection.3.1.1} {...

    Mask 98 for PRwin98

    to the Windows 3.1 user interface... Taskbar with versatile Start Menu, nested to any level Wastepaper bin to store deleted files and folders Desktop and file based shortcuts to any object or URL ...

    rm2.6正式版本

    Its capabilities comparable with in QuickReport,ReportBuilder. It written on 100% Object Pascal and can be installed in Delphi 2/3/4/5/6 and C++Builder 1/3/4/5/6. &lt;br&gt;2.特点 ---- ...

    达内 coreJava 习题答案

    1,编写程序,判断给定的某个年份是否是闰年。 闰年的判断规则如下: (1)若某个年份能被4整除但不能被100整除,则是闰年。 (2)若某个年份能被400整除,则也是闰年。 import java.util.Scanner;...

    AD630锁相放大资料

    hybrid or IC balanced modulator/demodulator and is comparable to that of costly signal processing instruments. 4. The op amp format of the AD630 ensures easy implementation of high gain or complex ...

Global site tag (gtag.js) - Google Analytics