I am passing a String name
to a method, if that name
isn't in the array then it gets added.
I tried this first but got Concurrent Modification Exception
List<String> people = new ArrayList<>();
public void addName(String name) {
if (people.isEmpty()) {
people.add(name);
} else {
for (String s : people) {
if (s.equals(name)) {
System.out.println("dont add");
} else {
people.add(name);
}
}
}
}
After reading on forums I learned you have to use iterator to avoid this. I tried it and fixed the Concurrent Modification Exception
, but the player gets added even though I stated them not to be added if they exist in the array, I do get this output "name exists" when I pass a name already existing in the list, but then it runs "name added" as well so dont understand why this is happening
if (people.isEmpty()) {
people.add(name);
} else {
String name2 = null;
for (Iterator<String> it = people.iterator(); it.hasNext(); ) {
String element = it.next();
if (element.equals(name)) {
String message = "name exists";
System.out.println(message);
name2 = null;
} else if (!element.equals(name)) {
System.out.println("Name added");
name2 = name;
}
}
if (name2 != null) {
people.add(name2);
}
}
You can do it simply by:
public void addName(String name) {
if (!people.contains(name)) {
people.add(name);
}
}
It sounds like you are trying to re-invent a set.
Set<String> names = new TreeSet<>(); // Or set of your choice
names.add("Joe"); // Set contents ["Joe"]
names.add("Bob"); // Set contents ["Joe", "Bob"];
names.add("Joe"); // Set contents ["Joe", "Bob"];
If you want to have the printlines
if (names.add(name) {
System.out.println("Added name " + name);
} else {
System.out.println("Already added " + name);
}
I reckon you need to break out of your loop once you find that the name already exists. Otherwise name2
might get set to null
and then set to a non-null value again.
For example:
for (Iterator<String> it = people.iterator(); it.hasNext(); ) {
String element = it.next();
if (element.equals(name)) {
String message = "name exists";
System.out.println(message);
name2 = null;
break;
} else if(element.equals(name)==false) {
System.out.println("Name added");
name2 = name;
}
}
But do have a look at contains
since this is a much much cleaner approach!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.