我正在从数据库模型Income中获取数据。看起来就是这样
@Table(name = "Income")
public class Income extends Model {
@Column(name = "AmountDate")
public String amountDate;
@Column(name = "Amount")
public Double amount;
@Column(name = "Day")
public int day;
@Column(name = "Month")
public int month;
@Column(name = "Year")
public int year;
}
在我的片段中,我将从数据库中获取所有收入数据。在我的BaseAdapter中,我想创建带有月份和年份的ArrayList。看起来像这样
array = [{6, 2018}, {6, 2018}, {7, 2018}, {7, 2018} {8, 2018}]
,并且我希望从该数组中删除重复的项目,因此它看起来应该像array = [{6, 2018}, {7, 2018} {8, 2018}]
然后,我将在listview和onListViewItem中显示的数组中的数据将显示选定月份的所有数据。
这是我的BaseAdapter代码
private class IncomeArrayAdapter extends BaseAdapter {
private LayoutInflater inflater;
private List<Income> incomeList;
List<Income> listOfIncomes = new ArrayList<>();
public IncomeArrayAdapter(List<Income> incomesList) {
inflater = LayoutInflater.from(getActivity());
this.incomeList = incomesList;
for (int i = 0; i < this.incomeList.size(); i++) {
listOfIncomes.add(this.incomeList.get(i));
}
Set<Income> setOfIncomes = new HashSet<>(listOfIncomes);
listOfIncomes.clear();
listOfIncomes.addAll(setOfIncomes);
for (int i = 0; i < listOfIncomes.size(); i++) {
System.out.println(listOfIncomes.get(i).month + listOfIncomes.get(i).year);
}
}
}
我对Java很陌生,所以我的问题是如何创建新的ArrayList并从该列表中删除重复项?
编辑:
正如我建议将equals
和hashCode
实现到我的Income
模型中一样。
这两种方法的实现有些麻烦。因此,我还将编辑我的问题。
public int hashCode() {
return month + year;
}
public boolean equals(Object o) {
boolean flag = false;
return flag;
}
我的equals
和hashCode
实施应如何显示?
答案 0 :(得分:1)
大多数IDE都有一种自动生成哈希码和等于函数的方法。在IntelliJ IDEA中,按Alt +插入(或右键单击>生成...)
然后单击“ equals()和hashCode()”
或者在Eclipse中,右键单击源上的某个位置,然后选择: “源”>“生成hashCode()和equals()...”
无论哪种方式,它都会为您的班级产生类似以下的内容:
public class Income extends Model {
public String amountDate;
public Double amount;
public int day;
public int month;
public int year;
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((amount == null) ? 0 : amount.hashCode());
result = prime * result + ((amountDate == null) ? 0 : amountDate.hashCode());
result = prime * result + day;
result = prime * result + month;
result = prime * result + year;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Income other = (Income) obj;
if (amount == null) {
if (other.amount != null)
return false;
} else if (!amount.equals(other.amount))
return false;
if (amountDate == null) {
if (other.amountDate != null)
return false;
} else if (!amountDate.equals(other.amountDate))
return false;
if (day != other.day)
return false;
if (month != other.month)
return false;
if (year != other.year)
return false;
return true;
}
}