我尝试以两种不同的方式对 arrayList 进行排序,一种是按 arrayList 内对象的面积排序,另一种是按 arrayList 中对象的名称(shape1,shape2)排序。当我将它们打印到文件中时,这些对象看起来像这样: shape1: (点、半径等...)面积 = 0.0 并且形状继续前进。我尝试查看其他类似但都使用 Collections.sort 回答的问题。我不确定我应该使用这种方法。这是我正在使用的一些代码,可以为您提供一些想法:
for (int i =0; i <shapes.size();i++){
for (int j = 1; j<shapes.size(); j++){
if (shapes.get(i).getShape().area() > shapes.get(j).getShape().area())
{
//
}
else
{
//
}
}
}
我不知道该怎么做。有什么指点吗?对于按名称排序,我必须使用:
shapes.get(i).getName()
最佳答案
解决方案1
您对象可以实现 Comparable接口(interface)及使用Collections.sort(List list)进行排序。
public class Shape implements Comparable<Shape> {
@Override
public int compareTo(Shape o) {
if(o == null) {
return 1;
}
if(getName() == null || o.getName() == null) {
return 0;
} else if(getName() != null && o.getName() == null) {
return 1;
} else if(getName() == null && o.getName() != null) {
return -1;
}
return getName().compareTo(o.getName());
}
}
Collections.sort(shapes);
解决方案2
创建一个实现 Comparator 的类并使用Collections.sort(List list, Comparator c)
public class ShapeComparator implements Comparator<Shape> {
@Override
public int compare(Shape s1, Shape s2) {
if(s1 == null || s2 == null) {
return 0;
} else {
return s1.getName().compareTo(s2.getName());
}
}
}
Collections.sort(shapes, new ShapeComparator());
关于java - 如何在java中按对象的组件对数组列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10291406/