Java中创建ArrayList赋值后排序

来源:互联网 发布:地下停车场出租软件 编辑:程序博客网 时间:2024/06/05 17:53

代码均在jsp页面上编写

先引用以下包

<%@ page import="java.util.ArrayList" %><%@ page import="java.util.Collections" %><%@ page import="java.util.Comparator" %>

自定义一个类,<%!  代码 %> 这种写法可以直接在jsp页面上写类或函数,挺方便的,注意感叹号!

<%!class Account{private String typec;private String budat;private String wrbtr_6;private String wrbtr_1;private String wrbtr_2;private String budat2;public Account(){}public Account(String typec,String budat,String wrbtr_6,String wrbtr_1,String wrbtr_2,String budat2){this.typec=typec;this.budat=budat;this.wrbtr_6=wrbtr_6;this.wrbtr_1=wrbtr_1;this.wrbtr_2=wrbtr_2;this.budat2=budat2;}public String getTypec(){return this.typec;}public String getBudat(){return this.budat;}public String getWrbtr_6(){return this.wrbtr_6;}public String getWrbtr_1(){return this.wrbtr_1;}public String getWrbtr_2(){return this.wrbtr_2;}public String getBudat2(){return this.budat2;}}%>


然后可以下面就创建ArrayList并且赋值,排序

List<Account> accounts=new ArrayList<Account>();Account account1=new Account("TYPEC,"2014-11-29","WRBTR_6","WRBTR_1","WRBTR_2","BUDAT2");Account account2=new Account("TYPEC,"2014-12-01","WRBTR_6","WRBTR_1","WRBTR_2","BUDAT2");Account account3=new Account("TYPEC,"2014-11-30","WRBTR_6","WRBTR_1","WRBTR_2","BUDAT2");accounts.add(account1);accounts.add(account2);accounts.add(account3);

//ArrayList排序Collections.sort(accounts, new Comparator<Account>() {@Overridepublic int compare(Account o1, Account o2) {if (o1 != null && o2 != null) {if (o1.getBudat().compareTo(o2.getBudat())<0) {return 1;}else if (o1.getBudat().compareTo(o2.getBudat())>0) {return -1;}}return 0;}         });

for(Account a : accounts){out.print(a.getTypec()+"---"+a.getBudat()+"---"+a.getWrbtr_6()+"---"+a.getWrbtr_1()+"---"+a.getWrbtr_2()+"<br>");}



0 0