开发者

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:

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. How to solve this? Must I change the type ArrayList ID to another java collection?


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:

  1. Sets are guaranteed to contain only unique values
  2. Adding the same value again has no effect
  3. Passing a collection to the constructor of a collection adds all elements from the parameter to the new collection


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. 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, e.g. a 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, e.g.

Set<Integer> uniqueCollection = new HashSet<Integer>(myArrayList);

... which will only hold unique values out of your List.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜