java - register problem
When i try to register a person with the name Eric for example, and then again registrating Eric it works. This should not happen with the code i have. Eric should not be registrated if theres already an Eric in the list. Here is my full code:
private Person findName(String name) {
for (Person person : personer) {
开发者_如何学JAVA if (person.getName() == name) {
return person;
}
}
return null;
}
private boolean containsName(String name) {
return findName(name) != null;
}
Your problem is with this line:
if (person.getName() == name)
You want
if (person.getName().equals(name))
In Java, "==" is reference equality for non-primitive types. The reference to name
(i.e., its "address", if you will) isn't the same as the reference to the object returned by getName()
.
See also: http://www.java-samples.com/showtutorial.php?tutorialid=221
Brian's answer is correct. However, on a "forest instead of trees" level, the code's design needs to be fixed too:
If you want a collection of sorted names, and be able to search for existing names, you should be using a TreeMap
. An ArrayList
(that you sort on each insertion, no less) is totally the wrong data structure for this.
精彩评论