我建议两种方法来解决你的问题。第一个是坚持使用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 ...
}
在这个代码片段中,我们遍历列表中的所有项目,直到我们发现玩家已经存在。如果您的列表中不存在此类播放器,它将以hasMyItem
的值为false
退出,在这种情况下,您会将新播放器添加到列表中。
迭代列表中的所有项目是一种常用的方法,它绝对是一件好事。但是,您可能会考虑使用另一个名为Map<Key, Value>
的数据结构。 Map
将Key
与Value
相关联,并将它们像列表一样存储在Map中。
你可以认为Map<Key, Value>
作为标签项目。 Key
是每个项目的标签。假设你的桌子上有一堆笔记本,并且你想找到一个数学笔记。如果您知道数学笔记的独特标签,例如封面上的一些文本或图像,您可以毫不费力地找到它。在你的例子中,Key
将成为用户名,Value
将成为玩家。
Map
有什么好处?它提供了一种简单的方法来查找您拥有的Key
值。如果您使用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
}
有由Map<K,V>
提供其他有用的方法,其可以被发现here。
作为一个附注,每当你可以声明每个班级成员为private
,而不是default
(这是你什么时候不指定任何内容)或public
。关于为什么你应该这样做有很多讨论,但基本上是为了保护你自己的代码不受其他人的伤害。你可以很容易地搜索,但这里有一些链接。 Link1Link2
我希望这可以给你一些很好的起点。
'Add'应是'add'。案件事宜 –
谢谢,我知道。不幸的是我使用Java和C#并且总是这样做是错误的:) – Snaff