comparable接口,arrayList中对象排序

comparable接口,arrayList<>排序

https://blog.csdn.net/chunxiaqiudong5/article/details/52760058

 

1.要比较的实体类继承Comparable接口

2.重写comparaTo()方法;在该方法中可以设置计较策略,

result=this.age.compareTo(o.getAge());

result==0 表示this.age == o.getAge()

result == 1 表示 this.age > o.getAge()

result ==-1 表示this.age <o.getAge()

3.Collection.sort(sList);

 

package com.example.study.comparabel;



/**

* @program: demo

* @description: 测试实体类

* @author: sjk

* @create: 2018-09-13 15:23

**/

public class Student implements Comparable<Student> {



private Integer age;

private Integer score;

private String name;



public Student(Integer age, Integer score, String name) {

this.age = age;

this.score = score;

this.name = name;

}



public Integer getAge() {

return age;

}



public void setAge(Integer age) {

this.age = age;

}



public Integer getScore() {

return score;

}



public void setScore(Integer score) {

this.score = score;

}



public String getName() {

return name;

}



public void setName(String name) {

this.name = name;

}





@Override

public String toString() {

return "Student{" +

"age=" + age +

", score=" + score +

", name='" + name + '\'' +

'}';

}





@Override

public int compareTo(Student o) {

//o是当前传入的 strudent

//this 是下一个要比较的student

//this.age和o.age 相等 result=0

//this.age>o.age result=1

//this.age<o.age result=-1



int result =0;

result=this.age.compareTo(o.getAge());

if(result==0){

result=this.score.compareTo(o.getScore());

}



return result;

}

}

import org.junit.Test;



import java.util.ArrayList;

import java.util.Collection;

import java.util.Collections;

import java.util.List;



/**

* @program: demo

* @description: 测试

* @author: sjk

* @create: 2018-09-13 15:30

**/

//@RunWith(SpringRunner.class)

//@SpringBootTest

public class ComparableTest {



@Test

public void test1() {



List<Student> sList = new ArrayList<>();

Student s1 = new Student(18,80,"张三");

Student s2 = new Student(19,81,"张四");

Student s3 = new Student(20,83,"张五");

Student s4 = new Student(20,82,"张六");



sList.add(s2);

sList.add(s3);

sList.add(s4);

sList.add(s1);

Collections.sort(sList);

for (Student s : sList) {

System.out.println(s.toString());

}

}



}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值