Java – objects to list – > Why do I create a new object?
•
Java
I want to know why:
Data type library
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 as 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 has the first element 1 / Berlin and the second 8 / m ü nchen But I don't understand this:
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 I don't create a new object library as shown above, the list contains 8 / m ü nchen. Twice Why is that? I don't understand this because when I add the first element, it contains 1 / Berlin Then I override the value and add a second one
thank you
Solution
You are modifying an existing list List allows copying, it does not prevent you from adding objects with the same value twice To prevent duplication, you can do the following:
myHashSet = new HashSet<Bank>(bank);
then:
banks = new List<Bank>(myHashSet);
Duplicate set is not allowed
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码