How to limit the number of items that can be added to a list in a list

2830 views java
0

I have a list of lists in Java which has 3 lists of integers in it.

List<List<Integer>> L;
         myList = new ArrayList<>();
         for(int i=0; i<3; i++){
                myList.add(new ArrayList<Integer>());
         }
myList.get(0).add(1);
myList.get(0).add(2);
myList.get(0).add(3);
myList.get(0).add(4);
myList.get(1).add(1);
myList.get(1).add(2);
.
.
.

My problem is that the number of the items that can be added to each of lists is unlimited in my code, but I want to limit the number of the items that each list can get. For example, each list can get only 4 items and when the 5th item is received by one of these lists, I need a shift to the left so the 5th item can be added to the list. Here is an example of what I intend to do:

At first: myList = [[1,2,3,4],[1,2,3,4],[1,2,3,4]]

After the 5th item is added to the first list of myList: myList = [[2,3,4,5],[1,2,3,4],[1,2,3,4]]

I tried to limit the number by something like this:

for(int i=0; i<3; i++){
        myList.add(new ArrayList<Integer>(4));
 }

but it didn't work. How can I do this?

answered question

So, shat have you tried? What's the concrete problem you're facing?

Not quite the same, but basically the same topic only for queues

If you need the item limit to be applied automatically, then you'll need to create a custom List implementation for your inner lists. This is relatively easy to do by overriding AbstractList. Do note that the result, although it implements List, will not correctly satisfy the contract of that interface.

@JBNizet I'm new to Java. I wasn't sure about how I could do this.

You're supposed to do some research, experiments, attempts, tests before asking a question. You'll do that for your whole career. Read the docuentation of List, and try doing it. It seems pretty straightforward to implement, doesn't it?

@JBNizet I edited my post and added what I had done to solve the problem.

What you posted just adds 3 more empty lists to your outer list. You need a method that gets an inner list by its index, check if its size is 4, if it is, remove its first element, and then adds the new value to it.

1 Answer

3

1st method: Create a custom List/ArrayList whatever you want.

public class CustomArrayList extends ArrayList<Object> {
  @Override
  public boolean add(Object e) {
      if (this.size() < yourLimitSize) {
          return super.add(e);
      }
     // shift
      return false;
  }
}

2nd method:

wrap your list with:

if(list!= null && list.size() < yourLimitSize(){
list.add(yourElement)
}else{
  //  shift
}

posted this

Have an answer?

JD

Please login first before posting an answer.