手机版
你好,游客 登录 注册
背景:
阅读新闻

Java中对象比较和排序实例

[日期:2015-01-03] 来源:Linux社区  作者:Willard [字体:大 中 小]

Java中对象比较和排序实例

(1)对Element对象进行排序(根据体重和年龄)
 (2)要想使用Arrays.sort支持排序的类必须实现Comparable接口
 
public class Elephant  implements  Comparable {
 
 
 int weight ;
 int  age    ;
 float tusklength;
 @Override
 public int compareTo(Object o) {
 
  Elephant  otherelephant =(Elephant) o;
  if(this.weight>otherelephant.weight){
  return 1 ;
  }
  else if(this.weight
  return -1;
  }
  else {
  return (this.age-otherelephant.age);
  }
  }
 
 
/*
 * 根据Elephant类写的一个测试类对Elephant对象根据体重和年龄进行排序
 * */
import java.util.Arrays;
public class ElephantTest {
 public static void main(String[] args) {
 Elephant elephant1 =new Elephant();
 elephant1.weight=1000;
 elephant1.age  =10;
 Elephant elephant2=new Elephant();
 elephant2.weight=200;
 elephant2.age  =200;
 
 Elephant elephant3=new Elephant();
 elephant3.weight=300;
 elephant3.age  =30 ;
 
 Elephant[] elephants =new Elephant[3];
 elephants[0]=elephant1;
 elephants[1]=elephant2;
 elephants[2]=elephant3;
 System.out.println("排序前!");
 for(Elephant  elephant:elephants){
  System.out.println("体重"+elephant.weight+":"+"年龄"+elephant.age);
 }
 Arrays.sort(elephants);
 System.out.println("排序后:");
 for(Elephant elephant:elephants){
  System.out.println("体重"+elephant.weight+":"+"年龄"+elephant.age);
 }
 }
}

Java中介者设计模式 http://www.linuxidc.com/Linux/2014-07/104319.htm

Java 设计模式之模板方法开发中应用 http://www.linuxidc.com/Linux/2014-07/104318.htm

设计模式之 Java 中的单例模式(Singleton) http://www.linuxidc.com/Linux/2014-06/103542.htm

Java对象序列化 http://www.linuxidc.com/Linux/2014-10/107584.htm

大话设计模式(带目录完整版) PDF+源代码 http://www.linuxidc.com/Linux/2014-08/105152.htm

本文永久更新链接地址:http://www.linuxidc.com/Linux/2015-01/111199.htm

linux
相关资讯       Java排序  Java对象 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款