今天不知道在哪里看过一个这样的题,我是这样实现的,实现的比较简单。- import java.util.*;
- public class Test0620 {
- /**
- * ArrayList如何实现插入的数据按自定义的方式有序存放
- */
-
- public static void main(String[] args) {
- ArrayList datas = new ArrayList();
- datas.add(new MyBean(11));
- datas.add(new MyBean(23));
- datas.add(new MyBean(12));
- Collections.sort(datas, new MyComparator());
- System.out.println(datas);
- }
- }
- class MyBean
- {
- private int age;
- MyBean(int age){
- this.age=age;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- @Override
- public String toString(){
- return this.age+"";
- }
- }
- class MyComparator implements Comparator{
- public int compare(Object o1,Object o2){
- MyBean s1 = (MyBean)o1;
- MyBean s2 = (MyBean)o2;
-
- //如果名称相同,还要比较年龄是否相同,因为年龄是int型,没有compareTo方法,所以封装成Integer对象
- int num = new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));
- return num;
- }
- }
复制代码 |