肯定是Object中的方法呀,,必须还要重写equals方法,这是我个人总结的List集合的一些技巧
主要总结了List集合宗去掉重复元素与排序(包括自然排序与自定义比较器排序),希望对你有帮助呀
- package com.cg.test;
- /*
- * List集合去除重复元素的方法,并且进行对指定比较器进行排序
- * */
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.Comparator;
- import java.util.Iterator;
- import java.util.LinkedList;
- import java.util.List;
- class Student implements Comparable<Student>{
- public String name;
- public int age;
- Student(String name,int age) {
- this.name=name;
- this.age=age;
- }
- public boolean equals(Object o1){
- if(!(o1 instanceof Student))
- return false;
- Student s=(Student)o1;
- return this.name.equals(s.name)&&this.age==s.age;
- }
- public int compareTo(Student o) {
- int num=this.age-o.age;
- return num==0?this.name.compareTo(o.name):num;
- }
-
- }
- class MyComparator implements Comparator<Student>{
- public int compare(Student o1, Student o2) {
- int num=o1.name.compareTo(o2.name);
- return num==0 ? o1.age-o2.age:num;
- }
- }
- public class CollectionsDemo {
- public static void main(String[] args) {
- showArrayList();
- }
- public static void showArrayList(){
- LinkedList<Student> alList=new LinkedList<Student>();
- //List<Student> alList=new ArrayList<Student>();
- alList.add(new Student("zhangsan",20));
-
- alList.add(new Student("lisi002",22));
- alList.add(new Student("lisi004",23));
- alList.add(new Student("lisi001",21));
- alList.add(new Student("lisi004",23));
- alList.add(new Student("lisi001",21));
- alList=singleArray(alList);
- Collections.sort(alList,new MyComparator());
- Iterator<Student> it=alList.iterator();
- while(it.hasNext()){
- Student s=it.next();
- System.out.println(s.name+"::"+s.age);
- }
- }
- public static LinkedList<Student> singleArray(LinkedList<Student> alList){
- LinkedList<Student> newal=new LinkedList<Student>();
- Iterator<Student> it=alList.iterator();
- while(it.hasNext()){
- Student s=it.next();
- while(!newal.contains(s)){
- newal.add(s);
- }
- }
- return newal;
- }
- }
复制代码
去重复与排序问题List集合通用哦 |