LinkedList集合之理解及集合之排序
LinkedList构造函数参数也不能传递 比较器对象,而且本身不具备比较功能。
如果想对LinkedList中的元素进行比较,需要使用Collections中的sort方法来处理。
如上面两个sort方法阐述。
具体细节请参照本人文档:LinkedList集合之理解及集合之排序!
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
public class LinkedListSummarize {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
operateObject();
}
public static void operateObject(){
Employer employer1 = new Employer("liyuandao", 33, 12000);
Employer employer6 = new Employer("rendahua", 52, 11000);
Employer employer2 = new Employer("xiashengbin", 27, 6000);
Employer employer3 = new Employer("luojiahui", 53, 9000);
Employer employer4 = new Employer("liudehua", 39, 11000);
Employer employer5 = new Employer("zhourenfa", 43, 20000);
LinkedList<Employer> linkedList = new LinkedList<Employer>();
linkedList.add(employer1);
linkedList.add(employer2);
linkedList.add(employer3);
linkedList.add(employer4);
linkedList.add(employer5);
linkedList.add(employer6);
printLinkedList(linkedList);
System.out.println("After sorted by natural ordering(Employer's name)");
Collections.sort(linkedList);
printLinkedList(linkedList);
System.out.println("After sorted by salary(used comparator)");
Collections.sort(linkedList, new EmployerComparator());
printLinkedList(linkedList);
}
public static void printLinkedList(LinkedList<Employer> linkedList){
for (Iterator<Employer> iterator = linkedList.iterator(); iterator.hasNext();) {
Employer employer = iterator.next();
System.out.println(employer.toString());
}
}
}
import java.util.Comparator;
public class Employer extends Person implements Comparable<Employer>{
/*
* salary
*/
private int salary;
public Employer(String name, int age, int salary){
super(name, age);
this.setSalary(salary);
}
@Override
public int compareTo(Employer employer){
int num = this.getName().compareTo(employer.getName());
if(num == 0){
return (new Integer(this.getAge())).compareTo(employer.getAge());
}
return num;
}
public void setSalary(int salary) {
this.salary = salary;
}
public int getSalary() {
return salary;
}
public String toString(){
return this.getName() + "::" + getAge() +"..."+ this.salary;
}
}
class EmployerComparator implements Comparator<Employer>
{
@Override
public int compare(Employer employer1, Employer employer2)
{
int num = new Integer(employer1.getSalary()).compareTo(new Integer(employer2.getSalary()));
if(num == 0)
{
return employer1.getName().compareTo(employer2.getName());
}
return num;
}
}