gpt4 book ai didi

java - 如何在java中使用比较器来比较diff对象值

转载 作者:行者123 更新时间:2023-12-02 07:57:13 29 4
gpt4 key购买 nike

  public  void dataAnalytics()
{
double sum=0;
double i=0;
double minage=20;
double maxage=20;

System.out.println("dataAnalytics for the Rural region");

for (Record ee :RList)
{
sum=sum+Double.valueOf(ee.getIncome());
i++;

if (ee.getAge()<20)
minage=ee.getAge();
if (ee.getAge()>20)
maxage=ee.getAge();

}
System.out.println("Average income for the Rural region is : $"+sum/i);
System.out.println("Min age for the Rural region is : "+minage);
System.out.println("Max age for the Rural region is : "+maxage);

}

我用java编写了以下代码,它遍历数组列表RList并计算所有收入元素的总和,然后取平均值。它的另一个功能是计算最大值和最小值。如何使用 java 比较器类完成相同的操作?

最佳答案

class AgeComparator implements Comparator {

public int compare( Object o1, Object o2 ){

int age1 = ((Record)o1).getAge();
int age2 = ((Record)o2).getAge();

if ( age1 > age2 ){ return 1; }
else if ( age1 < age2 ){ return -1; }
return 0;
}

}

public void dataAnalytics(){

Record[] records = rList.toArray();
Arrays.sort( records, new AgeComparator() );

int maxAge = (records[0]).getAge();
int minAge = (records[ records.length - 1]).getAge();

System.out.println("Min age for the Rural region is : " + minAge );
System.out.println("Max age for the Rural region is : " + maxAge );

}

关于java - 如何在java中使用比较器来比较diff对象值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9449333/

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