一件货物,具有两个属性,价格和重量,按照价格低优先,重量高优先原则排序
一、实现Comparable接口
package com.learn.bean;
public class Goods implements Comparable{
private Integer price;
private Integer kg;
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
public Integer getKg() {
return kg;
}
public void setKg(Integer kg) {
this.kg = kg;
}
public Goods(Integer price, Integer kg) {
this.price = price;
this.kg = kg;
}
public Goods() {
}
@Override
public String toString() {
return "Goods{" +
"price=" + price +
", kg=" + kg +
'}';
}
@Override
public int compareTo(Object o) {
if(o instanceof Goods) {
Goods other = (Goods) o;
if (this.price > other.price) {
return 1;
} else if (this.price < other.price) {
return -1;
}else{
if(this.kg<other.kg){
return 1;
}else if (this.kg>other.kg){
return -1;
}else {
return 0;
}
}
// return 0;
}
throw new RuntimeException("输入的数据类型不一致");
}
}
测试代码
package com.learn.test;
import com.learn.bean.Goods;
import com.learn.bean.User;
import java.util.ArrayList;
import java.util.Collections;
public class CompareTest {
public static void main(String[] args) {
Goods goods1 = new Goods(10, 100);
Goods goods2 = new Goods(10, 200);
Goods goods3 = new Goods(20, 100);
Goods goods4 = new Goods(20, 200);
ArrayList<Goods> goods = new ArrayList<>();
goods.add(goods1);goods.add(goods2);goods.add(goods3);goods.add(goods4);
Collections.sort(goods);
System.out.println(goods);
}
}
二、实现Comparator接口
package com.learn.bean;
public class Goods{
private Integer price;
private Integer kg;
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
public Integer getKg() {
return kg;
}
public void setKg(Integer kg) {
this.kg = kg;
}
public Goods(Integer price, Integer kg) {
this.price = price;
this.kg = kg;
}
public Goods() {
}
@Override
public String toString() {
return "Goods{" +
"price=" + price +
", kg=" + kg +
'}';
}
}
编写一个类
package com.learn.bean;
import java.util.Comparator;
public class CC extends Goods implements Comparator<Goods> {
@Override
public int compare(Goods o1, Goods o2) {
if(o1.getPrice()>o2.getPrice()){
return 1;
}else if (o1.getPrice()<o2.getPrice()){
return -1;
}else {
if(o1.getKg()<o2.getKg()){
return 1;
}else if(o1.getKg()>o2.getKg()){
return -1;
}else {
return 0;
}
}
}
}
测试代码
package com.learn.test;
import com.learn.bean.CC;
import com.learn.bean.Goods;
import com.learn.bean.User;
import java.util.ArrayList;
import java.util.Collections;
public class CompareTest {
public static void main(String[] args) {
Goods goods1 = new Goods(10, 100);
Goods goods2 = new Goods(10, 200);
Goods goods3 = new Goods(20, 100);
Goods goods4 = new Goods(20, 200);
ArrayList<Goods> goods = new ArrayList<>();
goods.add(goods1);goods.add(goods2);goods.add(goods3);goods.add(goods4);
Collections.sort(goods,new CC());
System.out.println(goods);
}
}