4-3案例,为什么运行的结果排序不了吖

4-3案例,为什么运行的结果排序不了吖

package com.imooc.sort;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class GoodsTest {
 public static void main(String[] args) {
  // TODO Auto-generated method stub
     Goods g1=new Goods("s00001","手机",2000);
     Goods g2=new Goods("s00002","冰箱",5000);
     Goods g3=new Goods("s00003","电视机",3000);
     List<Goods> goodsList=new ArrayList<Goods>();
     goodsList.add(g1);
     goodsList.add(g2);
     goodsList.add(g3);
     //排序前
     System.out.println("排序前:");
     for(Goods goods:goodsList) {
      System.out.println(goods);
     }
     Collections.sort(goodsList);
     //排序后
     System.out.println("排序后:");
     for(Goods goods:goodsList) {
      System.out.println(goods);
     }
 }
}


public class Goods implements Comparable<Goods> {
 private String id;// 商品编号
 private String name;// 商品名称
 private double price;// 商品价格
 // 构造方法
 public Goods(String id, String name, double price) {
  super();
  this.id = id;
  this.name = name;
  this.price = price;
 }

 // getter和setter方法
 public String getId() {
  return id;
 }
 public void setId(String id) {
  this.id = id;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public double getPrice() {
  return price;
 }
 public void setPrice(double price) {
  this.price = price;
 }
 
 
 @Override
 public String toString() {
  return "Goods [商品编号:" + id + ", 商品名称:" + name + ", 商品价格:" + price + "]";
 }
 @Override
 public int compareTo(Goods arg0) {
  // 取出商品价格
  double price1=this.getPrice();
  double price2=this.getPrice();
  int n=new Double(price2-price1).intValue();
  return n;
 }
}


正在回答 回答被采纳积分+1

登陆购买课程后可参与讨论,去登陆

1回答
好帮手慕珊 2017-09-26 09:14:43

public int compareTo(Goods arg0) {

  // 取出商品价格

  double price1=this.getPrice();

  double price2=this.getPrice();

  int n=new Double(price2-price1).intValue();

  return n;

 }

这段代码里,price1和price2都是this.getPrice(),有一个应该是方法的参数arg0去获得price的值,如:

 double price1=this.getPrice();

  double price2=arg0.getPrice();

祝学习愉快!

问题已解决,确定采纳
还有疑问,暂不采纳

恭喜解决一个难题,获得1积分~

来为老师/同学的回答评分吧

0 星
请稍等 ...
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号

在线咨询

领取优惠

免费试听

领取大纲

扫描二维码,添加
你的专属老师