I would suggest two ways to solve your problem. The first one is to stick with your approach of using List
.
List<Foo> list = new ArrayList<Foo>();
boolean hasMyItem = false;
String newName = "hello world";
for (Foo foo : list) // iterate over each item in the list
{
if (foo.name.equals(newName))
{
hasMyItem = true;
break; // get out of for loop
}
}
if (!hasMyItem)
{
list.add(new Foo(newName));
}
else
{
// the player is already in the list ...
}
In this code snippet, we are iterating over all of the items in the list until we find that the player already exists. If no such player exists in your list, it will exit with the value of hasMyItem
being false
, in which case you will add the new player to the list.
Iterating over all items in a list is a commonly used method and it's definitely good to know. However, you may consider using another data structure called Map<Key, Value>
. Map
associates a Key
with a Value
and store them together in the Map as like a list.
You could think Map<Key, Value>
as labeling items. Key
is a label for each item. Suppose you have a bunch of notebooks on your desk and you want to find a Math note. You can find it without much difficulty if you know the unique label of your math note, such as some texts or images on the cover page. In your example, the Key
will be the username, and Value
will be the player.
What's good with Map
? It provides a simple way to look for Key
values you have. The above codes can be more simplified if you use Map
.
Map<String, Foo> map = new HashMap<String, Foo>();
Foo f1 = new Foo("name1");
Foo f2 = new Foo("name2");
Foo f3 = new Foo("name3");
map.put("name1", f1);
map.put("name2", f2);
map.put("name3", f3);
// will return true and this if statement will be executed
if (map.containsKey("name1"))
{
// will be executed
}
// will return false because you don't have and this if statement will not be executed
if (map.containsKey("some new name"))
{
// will not be executed
}
There are other useful methods provided by Map<K,V>
, which can be found here.
As a side note, declare every class member as private
whenever you can, rather than default
(which is when you don't specify anything) or public
. There are many discussions of why you should do that, but basically it's to make protect your own codes safe from other people. You can search on this very easily but here are some links to it. Link1 Link2
I hope this can give you some good starting points.