java list.sort_Java List sort方法

packagecom.imooc.collection;import java.util.*;public classSetTest {private final List coursesToSelect = new ArrayList<>();private final Scanner scanner = newScanner(System.in);privateStudent student;publicSetTest(){

}//用于往courseToSelect中添加备选课程

public voidtestAdd(){//创建一个课程对象,并通过调用add方法,添加到备选课程List中

Course cr1 = new Course("1", "数据结构");

coursesToSelect.add(cr1);

Course cr2= new Course("2", "C语言");

coursesToSelect.add(0, cr2);//Course数组

Course[] course = {new Course("3", "离散数学"), new Course("4", "汇编语言")};

coursesToSelect.addAll(Arrays.asList(course));

Course[] course2= {new Course("5", "高等数学"), new Course("6", "大学英语")};

coursesToSelect.addAll(2, Arrays.asList(course2));

}/*** 通过 foreach 方法来遍历List*/

public voidtestForeach(){//System.out.println("(foreach)有如下课程待选:");

for(Object obj: coursesToSelect) {

Course cr=(Course) obj;

System.out.println("课程:" + cr.getId() + ":" +cr.getName());

}

}/*** 遍历Student集合中的所有元素

*@paramstudent*/

public voidtestForeachSet(Student student){//打印学生所选课程

for(Course cr: student.course) {

System.out.println("选择了课程:" + cr.getId() + ":" +cr.getName());

}

}/*** 测试List的 contains 方法

*@param

*/

public voidtestListContainers(){//获取备选课程序列的第0个元素

Course course = coursesToSelect.get(0);//打印输出coursesToSelected是否包含course对象

System.out.println("取得课程:" +course.getName());

System.out.println("备选课程中是否包含课程:" + course.getName() + "," +coursesToSelect.contains(course));//提示输入课程名称

System.out.println("请输入课程名称:");

String name=scanner.next();

Course course2= newCourse();

course2.setName(name);//创建一个新的课程对象, ID和名称 与course对象完全一样//Course course2 = new Course(course.getId(), course.getName());

System.out.println("新创建课程对象:" +course2.getName());

System.out.println("备选课程中是否包含课程:" + course2.getName() + ","+coursesToSelect.contains(course2));//通过indexOf()方法来获取某元素的索引位置

if(coursesToSelect.contains(course2)){

System.out.println("课程:" + course2.getName() + "的索引位置为:" +coursesToSelect.indexOf(course2));

}

coursesToSelect.sort(new Comparator() {

// 重写compare方法

@Overridepublic intcompare(Course o1, Course o2) {if(Integer.parseInt(o1.getId()) >Integer.parseInt(o2.getId())){return 0;

}return -1;

}

});for(Course cr: coursesToSelect){

System.out.println("课程ID:" + cr.getId() + "课程名称:" +cr.getName());

}

}public static voidmain(String args[]){

SetTest st= newSetTest();

st.testAdd();

st.testForeach();

st.testListContainers();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值