Is there a way to remove all empty cells in an ArrayList by just a built in function call? I saw trimToSize but I didn't really get what it meant.
For example, suppose I have an array that contains {1,2,3}. Lets say I say array.remove(1) so now the array looks like {1,null,3}. Is there a function to call to make it converge to be {1,3}?
I know I can hard code a method to do that for me but I was just curious.
3 Answers 3
That's exactly what remove does.
Removes the element at the specified position in this list. Shifts any subsequent elements to the left (subtracts one from their indices).
Now, if you're talking about arrays, not ArrayList, the answer is no.
1 Comment
If you are using an ArrayList, you don't need to worry about compacting the array after removing an element from it. The ArrayList class takes care of this kind of housekeeping.
If you are using an array, you could use the Commons Lang ArrayUtils class. The removeElement methods in this class simplify removing an element from an array and shifting all elements after it to the left.
Comments
In here you find a post that shows how to remove all null elements in a Collection
List<Integer> myList = new ArrayList<Integer>();
myList.add(1);
myList.add(2);
myList.add(null);
myList.add(3);
myList.add(null);
myList.add(4);
System.out.println("With null values");
for(Integer i: myList)
System.out.println(i);
myList.removeAll(Collections.singleton(null));
System.out.println("After deleting null values");
for(Integer i: myList)
System.out.println(i);
Output: With null values 1 2 null 3 null 4
After deleting null values 1 2 3 4
1 Comment
myList.removeAll(Collections.singleton(null)); line. You learn every day a new thing in SO :)
ArrayListis not a random Java term representing an array. It's a real Java class with real methods! Start here to learn about it: download.oracle.com/javase/tutorial/collections/index.html