// Removing elements from a list. // Removing is a relatively slow operation (except for removing // the last elemement) since ArrayList must slide down // all the elements after it. // Removing When you know the element's position arrayList.remove( i, object ); // Removing when you don't know the element's position. // This is slower that positional removing since ArrayList // must do a linear search for a match. It is faster if the list is // sorted, and you find the element first with a binarySearch. arrayList.add( object ); // Removing undesirable elements from the ENTIRE list. // You must work backwards. The list shrinks as we go. // E.g. removing empty Strings. for ( int i=arrayList.size(); i>=0; i-- ) { String element = (String)arrayList.get(i); if ( element == null || element.length() == 0 ) { arrayList.remove(i); } } // Removing undesirable elements from the TAIL END of a list. // You must work backwards. The list shrinks as we go. // E.g. removing empty Strings. for ( int i=arrayList.size(); i>=0; i-- ) { String element = (String)arrayList.get(i); if ( element == null || element.length() == 0 ) { arrayList.remove(i); } else { break; } } // Removing undesirable elements from the head end of a list. // You work forwards without incrementing, always working on element 0. // The list shrinks as we go. // E.g. removing empty Strings. while ( arrayList.size() > 0 ) { String element = (String)arrayList.get(0); if ( element == null || element.length() == 0 ) { arrayList.remove(0); } else { break; } } // If you just want to chop off the last m elements // This is most efficient. arrayList.setSize( arrayList.size() - m ); // Odd as it looks, this also removes a slice of the // ArrayList. It does not just nullify it. arrayList.subList( from, to ).clear();