java arraylist comparator,java – 使用Comparator对ArrayList排序对象

我在尝试按重量对这些Pet对象进行排序时遇到错误.我确信这很简单,但我不明白为什么这个比较不起作用.

Error: The return type is incompatible with java.util.Comparator.compare(Pet, Pet)

ArrayListNoDups类

import java.util.*;

import java.util.Collections;

import java.util.Comparator;

import java.lang.Object;

public class ArrayListNoDups {

public static void main(String[] args) {

ArrayList list = new ArrayList();

String name;

Integer age;

Double weight;

Scanner keyboard = new Scanner(System.in);

System.out.println("If you wish to stop adding Pets to the list, please put a 0 for all 3 fields.");

do {

System.out.println("Enter a String for Pet name: ");

name = keyboard.next();

System.out.println("Enter an int for Pet age: ");

age = keyboard.nextInt();

System.out.println("Enter a double for Pet weight: ");

weight = keyboard.nextDouble();

if (name.length() > 0 && age > 0 && weight > 0)

list.add(new Pet(name, age, weight));

} while (name.length() > 0 && age > 0 && weight > 0);

System.out.println("Your list sorted by WEIGHT ========================= ");

Collections.sort(list, Pet.SortByWeight);

for (Pet p2 : list)

p2.writeOutput();

}

}

宠物类

import java.util.*;

public class Pet {

private String name;

private Integer age; // in years

private double weight; // in pounds

public void writeOutput() {

System.out.println("Name: " + name);

System.out.println("Age: " + age + " years");

System.out.println("Weight: " + weight + " pounds");

}

public void set(String newName) {

name = newName;

// age and weight are unchanged.

}

public void set(int newAge) {

if (newAge <= 0) {

System.out.println("Error: illegal age.");

System.exit(0);

} else

age = newAge;

// name and weight are unchanged.

}

public void set(double newWeight) {

if (newWeight <= 0) {

System.out.println("Error: illegal weight.");

System.exit(0);

} else

weight = newWeight;

// name and age are unchanged.

}

public Pet(String name, int age, double weight) {

this.name = name;

this.age = age;

this.weight = weight;

}

public String getName() {

return name;

}

public int getAge() {

return age;

}

public double getWeight() {

return weight;

}

public static Comparator SortByWeight = new Comparator() {

public double compare(Pet pet1, Pet pet2) {

return pet1.getWeight() - pet2.getWeight();

}

};

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值