How to clear a list one by one in Java?

I would like to clear a list in Java as I loop through it.

This is how I loop through:

        for (CheckDetail checkDetail : checkDetails) {
            TableItem item = new TableItem(table, SWT.NULL);
            //item.setText(0, checkDetail.getStatus()); //Override
            //item.setText(1, checkDetail.getStatus()); //Rerun
            item.setText(0, checkDetail.getStatus()); //Status
            item.setText(1, checkDetail.getName()); //Check
            item.setText(2, checkDetail.getFileName()); //Filename
            item.setText(3, checkDetail.getExistingLineNumbers()); //Existing Line Numbers
            item.setText(4, checkDetail.getNewLineNumbers()); //New Line Numbers
            //This is to make shadow for every other line
            if (evenRow)
            evenRow = !evenRow;

Open in new window

Each time I get the information from one element I would like to remove it from the list. So , at the end when the for loop is complete I want the list to be empty.

How can I do it?
Who is Participating?
CEHJConnect With a Mentor Commented:
I would tend to use an Iterator explicitly

for(Iterator<CheckDetail> i = checkDetails.iterator();i.hasNext();) {
   CheckDetail CheckDetail =;
   // The same as before
   i.remove(); // clear

Open in new window

generally speaking you can not remove an item inside such this kind of loop,
try to use the index to loop over the list.

for(int i=0; i < checkDetails.getLength(); i++){ .... }
Sharon SethCommented:
Perhaps using an iterator is the only suggested way of  removing items from a list whilst iterating over it . The behaviour is unpredictable if you do it other ways . I remember when I was not using an iterator and modifying a list , it would end up with a ConcurrentModificationException
Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

TolgarAuthor Commented:
Perfect solution!
You can for-loop it backwards but i don't like it

for(int i = checkDetails.size();--i>=0;) {
   CheckDetail cd = checkDetails.get(i);
   // Do it

Open in new window

and anyway, you probably don't want to process in reverse order
TolgarAuthor Commented:
Thanks for the comments. I preferred to use the iterator.
Much better
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.