I have an array of objects in java. Something like this
array = [{month: 6, year: 2018, amount: 242}, {month: 6, year: 2018, amount: 345}, {month: 7, year: 2018, amount: 4567}, {month: 7, year: 2018, amount: 1234}, {month: 8, year: 2018, amount: 211}]
So I want to create a new array without duplicate month and year keys so this new array should look like this
newArray = [{month: 6, year: 2018}, {month: 7, year: 2018}, {month: 8, year: 2018}]
Here is function that I've implemented
private class IncomeArrayAdapter extends BaseAdapter {
private LayoutInflater inflater;
private List<Income> incomeList;
List<Income> listOfIncomes = new ArrayList<>();
public IncomeArrayAdapter(List<Income> incomesList) {
boolean found = false;
inflater = LayoutInflater.from(getActivity());
this.incomeList = incomesList;
for (int i = 0; i < incomeList.size(); i++) {
if (!listOfIncomes.contains(incomesList.get(i).month + incomesList.get(i).year)) {
listOfIncomes.add(incomesList.get(i));
}
}
}
So I've tried with hashCode() and equals() functions but I'm new to java and I failed. So I would like if some could help me and explain to me how to create this new array?
EDIT:
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
Income income = (Income) o;
return month == income.month &&
year == income.year;
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), month, year);
}
here is my hashCode() and equals() implementation.
It should return only one list object if month and year are equal.
containsto work the way you want it to, you should be passing anIncometo it. It looks like you're passing either aStringor anint(depending on what the types ofmonthandyearare).Incomeextends new abstract classAbstractIncomewhere you put filedmonthandyearsand you putamountin theIncomeclass