我需要帮助分类一个ArrayList<Usable>。Usable是一个在4个类中实现的接口,其中字段ID(是int)和日期(是日期变量)。
我如何分类这个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和日期的方法。
发布于 2014-01-30 15:38:35
假设您的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;
}
}发布于 2014-01-30 15:35:16
你必须创建一个像这样的界面:
interface MyInterface {
public int getID();
public Date getDate();
}并实现ArrayList<MyInterface>而不是ArrayList<Object>
List<MyInterface> arr = new ArrayList<>();类Vacanza、Bene、Cena和Prestazione必须实现接口MyInterface,并且可以将它们放入数组中。此外,你将避免这些可怕的铸造。
然后,您将能够调用Collections.sort(),并实现对数据进行排序的Comparator<MyInterface>。
https://stackoverflow.com/questions/21460438
复制相似问题