Menu

SetList

SetList provides an bridge between java.utilSet and java.util.List interfaces. This can be sometimes useful if you want use List methods like List.listIterator(int index) but don’t want allow duplicates in your List. For example SetList class can be used as an ArraySet if you decorate an ArrayList.

package org.happy.examples.collections.decorators.examples;

import java.util.ArrayList;
import java.util.List;

import org.happy.collections.lists.decorators.SetList_1x0;

import com.google.common.base.Preconditions;

/**
 * this example shows how a list can be decorated to not allow any dublicates
 * @author Andreas Hollmann
 *
 */
public class SetListExample {

    public static void main(String[] args) {
        boolean isSet = true;
        ArrayList<String> list = new ArrayList<String>();

        List<String> names = SetList_1x0.of(list, isSet);
        names.add("Andrej");
        names.add("Alexander");
        names.add("Alexej");

        boolean success = names.add("Andrej");
        Preconditions.checkState(!success);
        System.out.println(names);
    }

}

The output:

[Andrej, Alexander, Alexej]