定义Dog数组并通过接口排序-方法2/2
package com.iit.demo2; import java.util.Arrays; public class DemoArray2 { public static void main(String[] args) { Dog2[] dogs = new Dog2[5]; int index = 0; dogs[index++] = new Dog2("小黑1",15); dogs[index++] = new Dog2("小黑2",13); dogs[index++] = new Dog2("小黑3",11); dogs[index++] = new Dog2("小黑4",9); dogs[index++] = new Dog2("小黑5",3); Arrays.sort(dogs); for(Dog2 d:dogs){ System.out.println(d); } } }
package com.iit.demo2; public class Dog2 implements Comparable<Dog2> { private String name; private int age; public Dog2(){} public Dog2(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Dog{" + "name='" + name + '\'' + ", age=" + age + '}'; } @Override public int compareTo(Dog2 o) { return this.getAge()-o.getAge(); } }
本文来自博客园,作者:xiaoyongdata(微信号:xiaoyongdata),转载请注明原文链接:https://www.cnblogs.com/xiaoyongdata/p/16333358.html