Results 1 to 2 of 2
  1. #1
    Alpa is offline Member
    Join Date
    Dec 2011
    Posts
    17
    Rep Power
    0

    Default Add items to ArrayList when its size is equal to 0?

    Hi,

    I have an ArrayList which is being filled with items using a for-loop. Afterwards, I have some code that removes items from the list. Logically, after some time the size of my list is equal to 0, hence the program won't work. So I want the ArrayList to be filled with all items again when list.size() == 0.

    I tried this:
    Java Code:
    	    ArrayList<Integer> list = new ArrayList<Integer>();
    
    	    	for(int i = 0; i < 5; i++){
    	    		list.add(i);
    	    	}
    
    	    	if(list.size() == 0){
    	    		list.add(i);
    	    	}
    	}
    But it doesn't refill the list with its items. Any ideas how to achieve this? And why doesn't it work?

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: Add items to ArrayList when its size is equal to 0?

    That code shouldn't even compile since your second list.add(i), the i is out of scope of the for loop. And the code makes no sense since when it is called, the list will always have 5 items in it. You'll need to check the list where and when it is being used, not at list creation as your code above suggests.

    For more help, please give us more information about your problem.

Similar Threads

  1. checking array items are equal
    By trishtren in forum New To Java
    Replies: 5
    Last Post: 10-16-2011, 01:23 PM
  2. Replies: 8
    Last Post: 08-18-2011, 02:51 AM
  3. ArrayList size error
    By wepwep in forum New To Java
    Replies: 9
    Last Post: 03-29-2011, 10:57 AM
  4. Replies: 12
    Last Post: 11-05-2009, 08:12 AM
  5. Null Pointer Exception when adding items to ArrayList
    By ShadowCopy in forum New To Java
    Replies: 3
    Last Post: 08-27-2009, 10:23 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •