ArrayList排序

来源:互联网 发布:sql查询用户名密码 编辑:程序博客网 时间:2024/06/14 14:32

今天写一个小东西,要用到排序,好久不用了,都忘记了。。。。

话不多说,直接上代码

Student.java

public class Student {private String id;private String name;private String sex;private int source;public Student(String id, String name, String sex, int source) {super();this.id = id;this.name = name;this.sex = sex;this.source = source;}public String getId() {return id;}public String getName() {return name;}public String getSex() {return sex;}public int getSource() {return source;}@Overridepublic String toString() {// TODO Auto-generated method stubreturn this.getSource()+"";}}

 

重要的部分

MyComparator .java

import java.util.Comparator;public class MyComparator implements Comparator<Student> {public int compare(Student s1, Student s2) {if(s1.getSource() > s2.getSource()){return 1;} else if(s1.getSource() < s2.getSource()) {return -1;}return 0;}}


index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><%@page import="com.bean.Student"%><%@page import="com.bean.MyComparator"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><title>TestJSP</title></head><body><%Student s1 = new Student("001", "Jim", "男", 50);Student s2 = new Student("002", "Tom", "男", 70);Student s3 = new Student("003", "Dave", "男", 65);Student s4 = new Student("004", "Peter", "男", 80);Student s5 = new Student("005", "Lucy", "女", 100);//创建集合ArrayList<Student> list = new ArrayList<Student>();list.add(s1);list.add(s2);list.add(s3);list.add(s4);list.add(s5);Comparator comparator = new MyComparator();//重要部分Collections.sort(list, comparator);%><table border="1"><tr><td>ID</td><td>姓名</td><td>性别</td><td>成绩</td></tr><%for (Student s : list) {%><tr><td><%=s.getId() %></td><td><input type="text" value="<%=s.getName() %>"/></td><td><input type="radio" checked="checked"/><%=s.getSex() %></inp></td><td><%=s.getSource() %></td></tr><%}%></table></body></html>


 

原创粉丝点击