java的arraylist排序示例(arraylist用法)
时间:2020-11-08 12:16:58|栏目:JAVA代码|点击: 次
写了一个java数组排序示例,这里分享给大家共同学习
复制代码 代码如下:
package com.yonyou.test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Test {
public static void main(String[] args) {
Student zlj = new Student("丁晓宇", 21);
Student dxy = new Student("赵四", 22);
Student cjc = new Student("张三", 11);
Student lgc = new Student("刘武", 19);
List<Student> studentList = new ArrayList<Student>();
studentList.add(zlj);
studentList.add(dxy);
studentList.add(cjc);
studentList.add(lgc);
System.out.println("按照年?g排序:");
Collections.sort(studentList, new SortByAge());
for (Student student : studentList) {
System.out.println(student.getName() + " / " + student.getAge());
}
System.out.println(" ========= ");
System.out.println("按照姓名排序");
Collections.sort(studentList, new SortByName());
for (Student student : studentList) {
System.out.println(student.getName() + " / " + student.getAge());
}
}
}
class SortByAge implements Comparator {
public int compare(Object o1, Object o2) {
Student s1 = (Student) o1;
Student s2 = (Student) o2;
if (s1.getAge() > s2.getAge())
return 1;
else if (s1.getAge() == s2.getAge()) {
return 0;
}
return -1;
}
}
class SortByName implements Comparator {
public int compare(Object o1, Object o2) {
Student s1 = (Student) o1;
Student s2 = (Student) o2;
if(s1.getName().compareTo(s2.getName()) < 0)
return -1;
else if (s1.getName().compareTo(s2.getName()) > 0) {
return 1;
}
return 0;
}
}
class Student{
private int age;
private String name;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Student(String name,int age) {
this.age = age;
this.name = name;
}
}
栏 目:JAVA代码
下一篇:Spring Boot(四)之使用JWT和Spring Security保护REST API
本文标题:java的arraylist排序示例(arraylist用法)
本文地址:http://www.codeinn.net/misctech/20293.html
阅读排行
- 1Java Swing组件BoxLayout布局用法示例
- 2java中-jar 与nohup的对比
- 3Java邮件发送程序(可以同时发给多个地址、可以带附件)
- 4Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type异常
- 5Java中自定义异常详解及实例代码
- 6深入理解Java中的克隆
- 7java读取excel文件的两种方法
- 8解析SpringSecurity+JWT认证流程实现
- 9spring boot里增加表单验证hibernate-validator并在freemarker模板里显示错误信息(推荐)
- 10深入解析java虚拟机