[英]Java-I have an ArrayList contains objects, after one occurrence I want the object is added to another list
i have this ArrayList ID that contains objects:我有这个包含对象的 ArrayList ID:
0
10
10
9
8
3
11
6
10
1
7
13
7
7
After one occurrence of integer, i want that integer is added to another list (example visited) and the checking process stop.在一次出现 integer 之后,我希望将 integer 添加到另一个列表(访问示例)并且检查过程停止。 How to solve this?如何解决这个问题? Must I change the type ArrayList ID to another java collection?我必须将类型 ArrayList ID 更改为另一个 java 集合吗?
I think you are asking for all the unique values to be in another collection.我认为您要求所有独特的价值都在另一个集合中。 If so, do this:如果是这样,请执行以下操作:
List<Integer> list = Arrays.asList(0, 10, 10, 9, 8, 3, 11, 6, 10, 1, 7, 13, 7, 7);
Set<Integer> set = new HashSet<Integer>(list);
System.out.println(set); // Outputs "[0, 1, 3, 6, 7, 8, 9, 10, 11, 13]"
This works because:这是有效的,因为:
import java.util.HashSet;
public class Test {
private static final HashSet<Integer> onetimevisit = new HashSet<Integer>();
private static final HashSet<Integer> alreadyVisited = new HashSet<Integer>();
public static void addVisitor(Integer visitorId){
if(onetimevisit.contains(visitorId))
alreadyVisited.add(visitorId);
else
onetimevisit.add(visitorId);
}
}
If I am reading your question correctly, you want a collection containing unique values?如果我正确阅读了您的问题,您想要一个包含唯一值的集合吗? If that is the case, you should store these integers in a Set instead of a List to begin with.如果是这种情况,您应该将这些整数存储在 Set 而不是 List 中。 Sets contain unique values, and adding the same element multiple times has no effect.集合包含唯一的值,多次添加相同的元素没有效果。 If order is important in your collection, you can use an ordered Set, eg a LinkedHashSet.如果顺序在您的集合中很重要,您可以使用有序集合,例如 LinkedHashSet。
If you cannot change the ArrayList to a Set (because it is passed to your code in that form), you can build a set from the ArrayList, eg如果您无法将 ArrayList 更改为 Set(因为它以该形式传递给您的代码),您可以从 ArrayList 构建一个集合,例如
Set<Integer> uniqueCollection = new HashSet<Integer>(myArrayList);
... which will only hold unique values out of your List. ...它只会保留您列表中的唯一值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.