gpt4 book ai didi

java - 实现 java Comparable 类的问题

转载 作者:行者123 更新时间:2023-12-01 18:32:13 35 4
gpt4 key购买 nike

下图显示了在尝试实现位于我的 Tool 中的 compareTo() 方法时涉及 if-else 条件的编译错误类(class)。我不确定这个问题,因为该方法似乎是 public 并且在我的 Tool 类中(从中构造被比较的两个对象)。

Graphic showing compilation error.

public interface Product {
public abstract String getName();
public abstract double getCost();
}

public abstract class Vehicle implements Product {
private String name;
private double cost;

public Vehicle(String name, double cost) {
this.name = name;
this.cost = cost;
}

public String getName() {
return name;
}

public double getCost() {
return cost;
}
}

public class Car extends Vehicle {
public Car(String s, double d) {
super(s, d);
}
}

public class Truck extends Vehicle {
public Truck(String s, double d) {
super(s, d);
}
}

public class Tool implements Product, Comparable<Product> {
private String name;
private double cost;

public Tool(String name, double cost) {
this.name = name;
this.cost = cost;
}

public String getName() {
return name;
}

public double getCost() {
return cost;
}

public int compareTo(Product obj) {
if (getCost() < obj.getCost()) {
return -1;
} else if (getCost() == obj.getCost()) {
return 0;
} else {
return 1;
}
}
}

import java.util.*;
public class InventoryDemo
{
public static void main(String [] args) {
ArrayList<Product> list = new ArrayList<Product>();
list.add(new Car("Jagur", 1000000));
list.add(new Car("Neon", 17000));
list.add(new Tool("JigSaw", 149.18));
list.add(new Car("Jaguar", 110000));
list.add(new Car("Neon", 17500));
list.add(new Car("Neon", 17875.32));
list.add(new Truck("RAM", 35700));
list.add(new Tool("CircularSaw", 200));
list.add(new Tool("CircularSaw", 150));
list.add(new Tool("saw1", 200));
list.add(new Tool("saw2", 150));

if(list.get(9).compareTo(list.get(10)) == 0) {
System.out.println("\nThey are the same size using compareTo().");
} else {
System.out.println("\nThey are not the same size using compareTo().");
}
}
}

最佳答案

问题是您的列表类型为List<Product> ,但产品未实现Comparable接口(interface),因此该类型不实现该方法。

制作

public interface Product extends Comparable<Product> {
public abstract String getName();
public abstract double getCost();
}

关于java - 实现 java Comparable<T> 类的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23697869/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com