comparator与Comparable比较器

package work2;

import java.util.Arrays;
import java.util.Comparator;


public class ComparatorDemo {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  Cat[] cat = {new Cat("小黑","黑色",2),new Cat("小花","花色",1),new Cat("逗比","红色额",5),new Cat("小淘气","黑色",3)};
  Arrays.sort(cat, new CatComparator());
  System.out.println(Arrays.toString(cat));
 }

}


class CatComparator  implements Comparator{

 @Override
 public int compare(Cat cat1, Cat cat2) {
  // TODO Auto-generated method stub
  if(cat1.getAge() > cat2.getAge()){
   return 1;
  }else if(cat1.getAge() < cat2.getAge()){
   return -1;
  }
  return 0;
 }
 
}
class Cat{
 private String name;
 public Cat(String name, String color, int age) {
  this.name = name;
  this.color = color;
  this.age = age;
 }
 private String color;
 private int age;
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public String getColor() {
  return color;
 }
 @Override
 public String toString() {
  return "Cat [name=" + name + ", color=" + color + ", age=" + age + "]";
 }
 public void setColor(String color) {
  this.color = color;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
}

 

 

package work2;

import java.util.Arrays;
import java.util.TreeSet;

public class ComparableDemo {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
//  Dog[] dog = {new Dog("小黑",2,20),new Dog("小花",1,20),new Dog("小斗",3,20),new Dog("大黑",5,20),new Dog("小逗比",6,20)};
//  Arrays.sort(dog);
//  System.out.println(Arrays.toString(dog));
  TreeSet dog = new TreeSet();
  dog.add(new Dog("小黑",2,20));
  dog.add(new Dog("小花",1,20));
  dog.add(new Dog("小斗",3,20));
  dog.add(new Dog("大黑",5,20));
  dog.add(new Dog("大黑",5,30));
  System.out.println(dog);
 }

}

class Dog implements Comparable{
 private String name;
 private int age;
 @Override
 public String toString() {
  return "Dog [name=" + name + ", age=" + age + ", weight=" + weight
    + "]";
 }
 private int weight;
 public Dog(String name, int age, int weight) {
  this.name = name;
  this.age = age;
  this.weight = weight;
 }
 @Override
 public int compareTo(Object obj) {
  // TODO Auto-generated method stub
  Dog dog = (Dog)obj;
  if(this.age>dog.age){
   return 1;
  }else if(this.age
   return -1;
  }else{
   if(this.weight > dog.weight){
    return 1;
   }else if(this.weight < dog.weight){
    return -1;
   }
  }
  return 0;
 }
 
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值