我需要帮助对 ArrayList<Usable>
进行排序。 Usable
是一个用 4 个类实现的接口(interface),其中包含字段 ID(它是一个 int)和 Date(它是一个 Date 变量)。
如何对这个 ArrayList 进行排序?是否可以使用现有的方法,或者我必须自己创建完整的方法?
对于其他方法,我必须强制转换 Usable
对象特定的类以获得返回我想要的值的方法。例如,为了从 ArrayList 中删除产品,我使用了以下方法:
public void removeProd() {
...
//input product ID by user
...
int i;
boolean lol = false;
for (i=0; i<arr.size(); i++) {
if (arr.get(i) instanceof Vacanza) {
Vacanza v = (Vacanza) arr.get(i);
if (v.getvId() == ident) {
arr.remove(i);
lol = true; //... graphic message} }
else if (arr.get(i) instanceof Bene) {
Bene b = (Bene) arr.get(i);
if (b.getbId() == ident) {
arr.remove(i);
lol = true; //... graphic message}}
else if (arr.get(i) instanceof Cena) {
Cena c = (Cena) arr.get(i);
if (c.getcId() == ident) {
arr.remove(i);
lol = true; //... graphic message}}
else {
Prestazione p = (Prestazione) arr.get(i);
if (p.getpId() == ident) {
arr.remove(i);
lol = true; //... graphic message}}
}
if (lol == false) {
//graphic negative result message
this.removeProd(); }
}
基于此方法,如何按ID和日期对数组进行排序?每个类都有通过 getID() 和 getDate() 返回 id 和日期的方法。
最佳答案
假设您的Usable
界面如下所示:
public interface Usable {
Date getDate();
Integer getId();
}
您可以像这样对Comparator
进行排序:
Collections.sort(usables, new Comparator<Usable>() {
@Override
public int compare(Usable o1, Usable o2) {
int dateComparison = o1.getDate().compareTo(o2.getDate()); //compare the dates
if (dateComparison == 0) { //if the dates are the same,
return o1.getId().compareTo(o2.getId()); //sort on the id instead
}
return dateComparison; //otherwise return the result of the date comparison
}
});
编辑以解决问题中的代码
您似乎没有正确利用您的Usable
界面。
如果 Vacanza
、Bene
、Cena
和 Prestazione
实现 Usable
,它们应该看起来像这样:
public class Vacanza implements Usable {
private Date date;
private Integer id;
public Date getDate() {
return date;
}
public Integer getId() {
return id;
}
}
如果您所有的具体实现都像这样(并且您的代码如果不编译则不应编译...),那么 removeProd()
看起来更像是:
int i;
boolean lol = false;
for (i=0; i<arr.size(); i++) {
Usable usable = arr.get(i);
if (usable.getId() == ident) {
arr.remove(i);
lol = true;
}
}
关于java - 按日期和 ID 对 ArrayList<Usable> 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21460438/