gpt4 book ai didi

java - 如何调用ArrayList中的每个数组并按年龄对ArrayList进行排序?

转载 作者:行者123 更新时间:2023-11-30 02:43:48 26 4
gpt4 key购买 nike

对于我的任务,我被要求执行以下操作:

  • 比较动物的年龄,以便将动物按照年龄从大到小的顺序排列。

我已经创建了 if 语句,如果我是正确的,应该执行此操作,但我不确定如何引用数组列表中的每个 Animal,因此我使用了伪代码并引用了 ArrayList 中的第一个数组作为“AL1”,第二个作为“AL2”,依此类推。

这是代码:

演示类(class)

import java.util.ArrayList;
public class Demo {

public static ArrayList<Animal> animalGroup; // make this an instance static variable to access in other class with main method;

public static void main(String[] args)
{
animalGroup = new ArrayList<>();

//Add new Animals with properties such as name and age?
animalGroup.add(new Wolf("Sam", 5));
animalGroup.add(new Parrot("George", 3));
animalGroup.add(new Wolf("Wesley", 7));
animalGroup.add(new Parrot("Pat", 10));

System.out.println("Compare Aimal ages" + AL1.getAge().compareTo(AL2.getAge, AL3.getAge(), AL4.getAge()));

int result = AL1AGE.compareTo(AL2AGE, AL3AGE, AL4AGE);

if(result == 3)
System.out.println(AL1.getName() + "comes before " + AL2.getName() + ", " + AL3.getName() + " and " + A|L4.getName());
if(result == 5)
System.out.println(AL2.getName() + "comes before " + AL3.getName() + ", " + AL4.getName() + " and after " + A|L1.getName());
if(result == 7)
System.out.println(AL3.getName() + "comes before " + AL4.getName() + " and after " + AL1.getName() + " and " + A|L2.getName());
else
System.out.println(AL4.getName() + "comes after " + AL1.getName() + ", " + AL2.getName() + " and " + A|L3.getName());

}

}

主方法调用

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

public class Main {


public static void main(String[] args)
{

System.out.println("************ArrayList after sorting************");


Collections.sort(animalGroup);
Collections.reverse(animalGroup);

for(Animal animal2 : animalGroup) {
System.out.println(animal2.getName()+","+animal2.getAge());
}
}
}

所需输出

Sam comes before George, Wesley and Pat
George comes before Wesley, Pat and after Sam
Wesley comes before Pat and after Sam and George
Pat comes after Sam, George and Wesley

任何有关如何实现预期结果的帮助将不胜感激,谢谢。

最佳答案

创建一个实现Comparator的类。像这样:

import java.util.Comparator;

public class AgeComparator implements Comparator<Animal>{
@Override
public int compare(Animal animal1, Animal animal2) {
if(animal1.getAge() < animal2.getAge()){
return 1;
} else if (animal1.getAge() > animal2.getAge()) {
return -1;
} else {
return 0;
}
}

}

并使用您为 Collections.sort() 创建的 AgeComparator 类对其进行排序。

public static void main(String[] args) {

System.out.println("************ArrayList after sorting************");

Collections.sort(animalGroup,new AgeComparator()); // Sort highest to lowest

for (Animal animal2 : animalGroup) {
System.out.println(animal2.getName() + "," + animal2.getAge());
}
}

关于java - 如何调用ArrayList中的每个数组并按年龄对ArrayList进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40838729/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com