java - Object to list -> why do I have to create a new object? -
i understand why following happens:
datatype bank
public class bank { string blz; string name; public string getblz() { return blz; } public void setblz(string blz) { this.blz = blz; } public string getname() { return name; } public void setname(string name) { this.name = name; } }
this works expected:
public list<bank> getsearchresult() { list<bank> banks = new arraylist<>(); bank bank = new bank(); bank.setblz("1"); bank.setname("berlin"); banks.add(bank); bank = new bank(); bank.setblz("8"); bank.setname("münchen"); banks.add(bank); return banks; }
the list hast first element 1 / berlin , second 8 / münchen. don't understand:
public list<bank> getsearchresult() { list<bank> banks = new arraylist<>(); bank bank = new bank(); bank.setblz("1"); bank.setname("berlin"); banks.add(bank); //bank = new bank(); bank.setblz("8"); bank.setname("münchen"); banks.add(bank); return banks; }
if don't create new object bank shown above, list contains 2 times 8 / münchen. why happen? don't understand this, because when add first element contains 1 / berlin. overwrite values , add second.
thanks
you're modifying existing list. list allows duplication, won't prevent add objects same value twice. prevent duplicates can this:
myhashset = new hashset<bank>(bank);
and then:
banks = new list<bank>(myhashset);
set doesn't allow duplication.
Comments
Post a Comment