防止arraylist中的重复条目 [英] Prevent duplicate entries in arraylist

查看:30
本文介绍了防止arraylist中的重复条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我创建了一些像这样的对象类

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中的重复条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆