简体   繁体   中英

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, eg 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, eg

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM