[英]Sorting objects in an ArrayList without using Collections.sort
[英]Sorting ArrayList full of objects by their id using Collections.sort(arrayListName)
我有一个清单类,它创建了一个充满对象 Item 的 ArrayList,它也是一个类。 我知道我必须调用Collections.sort(items);
为了对 ArrayList 进行排序(顺便说一下,它被称为 items)。 作业说我必须在Item类上使用接口,我不知道是否实现Comparator或Comparable,然后分别为compareTo()
方法或compare()
方法编写什么。 在我声明我的 ArrayList 之后,我也有Collections.sort(items)
调用,这可以吗?
编辑:我的老师刚刚澄清说她希望我们在 Item 类上实现Comparable<Item>
。
从 Java 8 开始:
List<Item> items = new ArrayList<>();
// add elements
Collections.sort(items, Comparator.comparingLong(Item::getId));
你必须实现Comparable
并且它会起作用Collections.sort
如果您需要一个新的比较器并且不想使用Comparable
您可以创建一个新的Comparator
并像这样使用它: Collections.sort(list, new MyComparator())
public class Fruit implements Comparable<Fruit>{
private String fruitName;
private String fruitDesc;
private int quantity;
public Fruit(String fruitName, String fruitDesc, int quantity) {
super();
this.fruitName = fruitName;
this.fruitDesc = fruitDesc;
this.quantity = quantity;
}
public String getFruitName() {
return fruitName;
}
public void setFruitName(String fruitName) {
this.fruitName = fruitName;
}
public String getFruitDesc() {
return fruitDesc;
}
public void setFruitDesc(String fruitDesc) {
this.fruitDesc = fruitDesc;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public int compareTo(Fruit compareFruit) {
int compareQuantity = ((Fruit) compareFruit).getQuantity();
//ascending order
return this.quantity - compareQuantity;
//descending order
//return compareQuantity - this.quantity;
}
}
来源: mkyong
Collections.sort()
有两个版本。
Collections.sort(List)和Collections.sort(List,Comparator) 。 一个接受一个List
,另一个接受一个List
和一个Comparator
的实例。 单个参数sort()
将期望您的类实现Comparable并覆盖compareTo()方法。 两个参数sort()
方法需要一个Comparator实例,其中您已经实现了Comparator
并覆盖了它的compare()方法。
一个对象应该实现Comparable
如果这是对类进行排序的清晰自然的方式,并且任何需要对类进行排序的人通常都希望这样做。
但是,如果排序是类的一个不寻常的用例,或者可能有多个排序顺序,那么Comparator
是更好的选择。
在我声明我的 ArrayList 之后,我也有 Collections.sort(items) 调用,这可以吗?
当您需要对List
进行排序时,您将调用sort()
。 在sort()
之后添加项目不会自动对List
进行排序以适应由于添加新元素而导致的列表项目排序的变化。
示例实现:
public int compareTo (Item other) {
return new Integer(this.getID()).compareTo(new Integer(other.getID()));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.