0

I need to have a list that has an "enabled" filter such as:

[
{
    "enabled": false,
    "value": {
        "number": 0
    }
},
{
    "enabled": true,
    "value": {
        "number": 1
    }
},
{
    "enabled": false,
    "value": {
        "number": 2
    }
},
{
    "enabled": true,
    "value": {
        "number": 3
    }
}
]

If i were to iterate over this list printing each "number" using either Iterable.iterator() or a standard for loop with get(i) it'd output this:

1, 3

and it's size() would return 2. But if i go ahead and enable the first element it would print instead:

0, 1, 3

and it's size() would return 3.

Is there a standard implementation of something like this?

The list would feature operations to work on the unfiltered version of it, so as to be able to actually toggle each element.

Machinarius
  • 3,637
  • 3
  • 30
  • 53

2 Answers2

1

I think the easiest way is going to be a custom collection that simply skips over elements to the next enabled element

public interface Enabled
{
    public boolean isEnabled();
}

public class EnabledCollection<T extends Enabled> implements List<T>
{
    private List<T> list = new ArrayList<T>();

    @Override
    public Iterator<T> iterator() {        
        Iterator<T> it = new Iterator<T>() {

            private int i = 0;

            @Override
            public boolean hasNext() {
                return i < list.size();
            }

            @Override
            public T next() {
                T o = list.get(++i);

                while (!o.isEnabled() && hasNext()) { o = list.get(++i); }

                return o;
            }

            @Override
            public void remove() {
                // todo
            }
        };

        return it;
    }

    @Override
    public T get(int i)
    {
        T o = list.get(i);

        while (!o.isEnabled() && i < list.size()) { o = list.get(++i); }

        return o;
    }

    // etc
}
T I
  • 9,785
  • 4
  • 29
  • 51
0

I think you have to override some standard object to get this results.

Example for List override: Problem overriding ArrayList add method

Community
  • 1
  • 1
surfealokesea
  • 4,971
  • 4
  • 28
  • 38