防止arraylist中的重复条目

编程入门 行业动态 更新时间:2024-10-17 11:34:08
本文介绍了防止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中的重复条目

本文发布于:2023-11-06 23:53:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1565002.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:条目   arraylist

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!