假设我像这样创建了一些对象类
public class thing {
private String name;
private Integer num;
public oDetails (String a, Integer b) {
name = a;
num = b;
}
...gets/ sets/ etc
现在我想创建一个数组列表来保存这个对象类的数量。
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,它将是
"Star Wars", 4
我很难想出一种优雅的方式来处理这个问题。随着 arraylist 的增长,搜索它以确定是否有重复的名称项变得很麻烦。任何人都可以提供一些指导吗?
最佳答案
您必须创建自己的方法来检查类 Thing 的 name
字段是否设置为“Star Wars”,然后添加到相应的 num
Class Thing 的字段,这是一种可能的解决方案。
另一种解决方案是使用 Map
,其中 name 字段作为键,num 字段作为值。
例如:
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());
}
}
希望这对您有所帮助。
关于java - 防止 arraylist 中的重复条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9962082/