1. 程式人生 > >Java自定義物件陣列、集合排序

Java自定義物件陣列、集合排序

//實體類:

package CategoryDp2;


import java.util.Comparator;


public class Cat implements Comparator<Cat>,Comparable<Cat>{
private int weight;

public int getWeight() {
return weight;
}


public void setWeight(int weight) {
this.weight = weight;
}


@Override
public int compare(Cat o1, Cat o2) {
if(o1.weight>o2.weight)
return 1;
else
return 0;
}


public Cat(int weight) {
super();
this.weight = weight;
}
@Override
public String toString(){
return this.weight+"";
}


@Override
public int compareTo(Cat o) {
return compare(this, o);
}
}

//測試類:

package CategoryDp2;


import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;


public class Test {
/**
* @param args
*/
public static void main(String[] args) {
//自定義物件陣列排序
Cat [] cats = {new Cat(22),new Cat(52),new Cat(2),new Cat(12) };
java.util.Arrays.sort(cats);
for(Cat c: cats)
{
System.out.print(c.getWeight()+",");
}

//集合排序 從大到小
ArrayList<Cat> catList= new ArrayList<Cat>();
catList.add(new Cat(22));
catList.add(new Cat(2));
catList.add(new Cat(12));
catList.add(new Cat(52));
catList.add(new Cat(32));

Collections.sort(catList, new Comparator<Cat>(){//內部類 直接new介面
@Override
public int compare(Cat o1, Cat o2) {
if(o1.getWeight()<o2.getWeight())
return 1;
else return 0;
}
});
System.out.println();
for(Cat c: catList)
{
System.out.print(c.getWeight()+",");
}
}
}