java为基本数据类型使用可比接口
抱歉,如果这是一个愚蠢的问题,我对编程比较陌生
基本上,我有一个家庭作业问题来创建一个邮局场景,该场景支持两种类型的邮件:航空邮件和海运邮件。对于每种类型,我都使用calcFee方法来计算总运输成本
家庭作业的第二部分要求扩展Item类,以便它实现Compariable接口,在该接口中,项目根据其calcFee值进行排序。现在我明白了,基本数据类型不能从可比较的接口中进行排序。因为问题特别要求使用可比较的界面,我是做错了什么,还是只是创建的程序不正确
任何帮助都将不胜感激
package homework3;
import java.util.ArrayList;
import java.util.Collections;
/**
*
* @author Josh
*/
public class Homework3 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
ArrayList<Item> items = new ArrayList();
items.add(new airItems(11, "josh", "sam", 295));
items.add(new airItems(11, "zosh", "sam", 295));
items.add(new seaItems(11, "aosh", "sam", 11, 12, 15));
Collections.sort(items);
for (Item i : items){
i.calcFee();
i.print();
}
}
}
class Item implements Comparable<Item>{
int id;
String from;
String to;
double fee;
public Item(int id, String from, String to){
this.id = id;
this.from = from;
this.to = to;
}
public void print(){
System.out.println("id: " + id + "\tFrom: " + from + "\tTo: " + to + "\tFee: " + fee);
}
public double calcFee(){
return 0;
}
@Override
public int compareTo (Item item1){
return this.fee.compareTo(item1.calcFee());
}
}
class airItems extends Item{
long weight;
public airItems(int id, String from, String to, int weight){
super(id, from, to);
this.weight = weight;
}
public void print(){
super.print();
System.out.println("Weight: " + weight);
System.out.println("");
}
@Override
public double calcFee(){
if (weight < 100){
fee = 2.5;
}
else if (weight < 200) {
fee = 5;
}
else if (weight < 300) {
fee = 7.5;
}
return fee;
}
}
class seaItems extends Item{
int length;
int width;
int depth;
public seaItems(int id, String from, String to, int length, int width, int depth){
super(id, from, to);
this.length = length;
this.width = width;
this.depth = depth;
}
@Override
public double calcFee(){
if (length <= 10 && width <= 10 && depth <= 10){
fee = 5;
}
else if (length <= 20 && width <= 20 && depth <= 20){
fee = 10;
}
if (length <= 50 && width <= 50 && depth <= 50){
fee = 5;
}
else if (length > 50 && width > 50 && depth > 50 ){
fee = 0;
}
return fee;
}
@Override
public void print(){
super.print();
System.out.println("Length: " + length + "\tWidth:" + width + "\tdepth" + depth);
System.out.println("");
}
}
# 1 楼答案
就我而言,基本数据类型可以与
Comparable
接口一起使用,但不鼓励使用,因为它太复杂,不必要,通常需要进行一些修改(尽管我不完全确定,所以不要相信我的话)对于您的任务,最简单的方法是创建一个新的
List<Item>
,并使用Comparable
接口对其进行排序,使用.stream
:我在这里使用了lambda表达式,但成员引用也是可以接受的:
(Item::calcFee)
现在,这不适用于
@Override
ofprint
函数,您必须重写toString
,因为函数需要返回字符串。这可以通过以下方式实现:结果是:
# 2 楼答案
使用
Double
的compare()
方法:如果
fee
尚未初始化,最好使用calcFee()
而不是fee
。除非你有无数的项目,否则它不会有太大的性能差异