我建議兩種方法來解決你的問題。第一個是堅持使用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