import java.util.LinkedList;
class Person{
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "{ 姓名:"+this.name+" 年龄:"+ this.age+"}" ;
}
}
public class Demo108 {
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.add(new Person("张三",19));
list.add(new Person("李四",9));
list.add(new Person("王五",15));
list.add(new Person("赵六",8));
sort(list);
System.out.println("集合的元素:" + list);
}
public static void sort(LinkedList list){
for(int i = 0 ; i< list.size()-1 ; i++){
for(int j = i+1 ; j<list.size() ; j++){
Person p1 = (Person) list.get(i);
Person p2 = (Person) list.get(j);
if(p1.age>p2.age){
list.set(i, p2);
list.set(j, p1);
}
}
}
}
}
JAVA小练习108——定义一个LinedList存储一批人对象,然后根据人的年龄进行存储
最新推荐文章于 2022-12-29 22:13:54 发布