問題描述
假設我創建了一些像這樣的對象類
Say I create some object class like so
public class thing {
private String name;
private Integer num;
public oDetails (String a, Integer b) {
name = a;
num = b;
}
...gets/ sets/ etc
現在我想創建一個數組列表來保存一些這樣的對象類.
Now I want to create an arraylist to hold a number of this object class like so.
ArrayList<thing> myList = new ArrayList<thing>;
thing first = new thing("Star Wars", 3);
thing second = new thing("Star Wars", 1);
myList.add(first);
myList.add(second);
我想包含某種邏輯,以便在這種情況下......當我們嘗試添加對象second"而不是向 arrayList 添加新對象時,我們將 second.getNum() 添加到 first.getNum().因此,如果您要遍歷 ArrayList 它將是
I would like to include some sort of logic so that in this case...when we try and add object "second" rather than add a new object to the arrayList, we add second.getNum() to first.getNum(). So if you were to iterate through the ArrayList it would be
"Star Wars", 4
我無法想出一種優雅的方式來處理這個問題.并且隨著數組列表的增長,搜索它以確定是否有重復的名稱項變得很麻煩.任何人都可以提供一些指導嗎?
I am having trouble coming up with an elegant way of handling this. And as the arraylist grows, searching through it to determine if there are duplicate name items becomes cumbersome. Can anyone provide some guidance on this?
推薦答案
您必須創建自己的方法來檢查類 Thing 的 name
字段是否設置為星球大戰"" 然后添加到 Class Thing 的相應 num
字段,這是一種可能的解決方案.
You would have to create your own method to check to see if the the name
field of class Thing was set to "Star Wars" then add to the corresponding num
field of Class Thing, that is one possible solution.
另一種解決方案是使用 Map
,其中 name 字段作為鍵,num 字段作為值.
Another solution is to use a Map
with the name field as the key, and the num field as the value.
例如:
public class Thing
{
private String name;
private int num;
public Thing(String name, int num)
{
this.name = name;
this.num = num;
}
}
public class ThingMap
{
Map<String, Integer> thingMap;
public ThingMap()
{
this.thingMap = new HashMap<>();
}
public void put(Thing t)
{
String k = t.getName();
Integer v = t.getNum();
if(thingMap.get(k) == null) //no entry exists
{
thingMap.put(k, v);
}
else //entry exists
{
//add to the current value
thingMap.put(k, thingMap.get(k) + v);
}
}
public Integer get(String k)
{
return this.thingMap.get(k);
}
}
public class TestThing
{
public static void main(String[] args)
{
ThingMap tMap = new ThingMap();
Thing a = new Thing("Star Wars", 3);
Thing b = new Thing("Star Wars", 1);
tMap.put(a);
tMap.put(b);
System.out.println("Current value: " + tMap.get(a.getName());
}
}
希望這會有所幫助.
這篇關于防止arraylist中的重復條目的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!