ArraySortDemo1

来源:互联网 发布:ubuntu连不上有线网 编辑:程序博客网 时间:2024/04/30 03:28
package ArraySort;
import java.util.Arrays;
public class ArraySortDemo1
{
public static void main(String[] args)
{
Dog o1 = new Dog("dog1", 1);
Dog o2 = new Dog("dog2", 4);
Dog o3 = new Dog("dog3", 5);
Dog o4 = new Dog("dog4", 2);
Dog o5 = new Dog("dog5", 3);
Dog[] dogs = new Dog[] { o1, o2, o3, o4, o5 };
System.out.println("排序前");
for (Dog d:dogs) {
System.out.println(d.getName());
}
System.out.println("排序后");
Arrays.sort(dogs);
for (Dog d:dogs) {
System.out.println(d.getName());
}
}
}
class Dog implements Comparable{
private String name;
private int weight;

public Dog(String name, int weight) {
this.setName(name);
this.weight = weight;
}

public int getWeight() {
return weight;
}

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

public void setName(String name) {
this.name = name;
}

public String getName() {
return name;
}
public int compareTo(Object o)
{
Dog d=(Dog)o;
if(this.getWeight()>d.getWeight())
return 1;
else if(this.getWeight()<d.getWeight())
return -1;
else
return 0;
}
}
原创粉丝点击