数组列表中的prevent重复的条目 [英] Prevent duplicate entries in arraylist

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

问题描述

说我喜欢创造一些这样的对象类

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

现在我想创建一个ArrayList来保存一些这个对象类的,像这样。

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);

我想包括某种逻辑,所以在这种情况下......当我们尝试并添加对象第二,而不是添加一个新的对象到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?

推荐答案

您必须创建自己的方法来检查,看是否类事情的的名称字段设置为星球大战,然后添加到类事情的相应 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.

另一种解决方案是使用地图的名称字段作为键,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());
   }

}

希望这有助于。

这篇关于数组列表中的prevent重复的条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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