我需要对ArrayList<Usable>
进行排序的帮助。 Usable
是用4个类实现的接口,其字段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;
}
}