Mert Kimyonşen
Mert Kimyonşen

Reputation: 47

How to add element to Arraylist until as I want to limit?

I am trying to solve a problem but the limit of array 1000 and problem giving a input unknown number. I just add element in ArrayList until size 1000 and stop the adding element. I try to the adding element the following codes but this is not my programming just trying.

Adding element 0 to 14. How can I add until size 10?

public static void main(String[] args) {
    ArrayList<Integer> str=new ArrayList<Integer>();
    int y=str.size();
    do
    {
        for(int i=0; i<15; i++)
            str.add(i);
        System.out.println(str);
    }
    while(y!=10);          
}

Upvotes: 1

Views: 3786

Answers (2)

danielR
danielR

Reputation: 297

You could implement your own version of an ArrayList that extends from that class, to hold a maximum value of your choice.

public class MyList<E> extends ArrayList<E> {

    private int maxSize; //maximum size of list

    @Override
    public boolean addAll(int index, Collection<? extends E> c) {
        //check if list + the new collection exceeds the limit size
        if(this.maxSize >= (this.size()+c.size())) {
            return super.addAll(index, c); 
        } else {
            return false;
        }
    }

    @Override
    public boolean addAll(Collection<? extends E> c) {
        //check if list + the new collection exceeds the limit size
        if(this.maxSize >= (this.size()+c.size())) { 
            return super.addAll(c); 
        } else {
            return false;
        }
    }

    @Override
    public void add(int index, E element) {
        if(this.maxSize > this.size()) { //check if the list is full
            super.add(index, element);
        }
    }

    @Override
    public boolean add(E e) {
        if(this.maxSize > this.size()) { //check if the list is full
            return super.add(e); 
        } else {
            return false; //don't add the element because the list is full.
        }
    }

    public int getMaxSize() {
        return maxSize;
    }

    public void setMaxSize(int maxSize) {
        this.maxSize = maxSize;
    }

}

And then you could do something like this:

MyList<Integer> test = new MyList<Integer>();
test.setMaxSize(10);
for(int i=0; i<15; i++) {
    test.add(i);
}

This would result in something like this:

test => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Upvotes: 4

Marcelo Tataje
Marcelo Tataje

Reputation: 3871

I'm not sure why are you using a loop inside a loop, but this will be my approach, according to a what I understand from your problem.

ArrayList<Integer> intList = new ArrayList<Integer>();

for (int i = 0; i < 15; i++) {
    if (intList.size() == 10) {
        break;
    }
    intList.add(i);
    System.out.println(intList.get(i));
}       

Hope this can give you a clue and you can find a solution to your problems.

Regards and happy coding.

Upvotes: 2

Related Questions