欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java的arraylist排序示例(arraylist用法)

程序员文章站 2024-02-26 22:58:28
写了一个java数组排序示例,这里分享给大家共同学习复制代码 代码如下:package com.yonyou.test;import java.util.arraylist...

写了一个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("按照年齡排序:");
  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;
 }
}