开发者

Array Lists in java

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 开发者_StackOverflow中文版I was just curious.


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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜