Monday, 20 September 2021

Small syntax difference ends up different result

Java ArrayList remove function

Assume we have a Integer array list arr


    arr.add(20);
    arr.add(30);
    arr.add(1);
    arr.add(10);
    
    arr.remove(new Integer(1));

    //will return [20, 30, 10]
    System.out.println(arr);
	

    arr.add(20);
    arr.add(30);
    arr.add(1);
    arr.add(10);
    
    arr.remove(1);

    //will return [20, 1, 10]
    System.out.println(arr);
	

In the first case, we are calling remove function from public interface java.util.Collection

public boolean remove(E element)

In the second case, we are calling remove function from public interface java.util.List

public Object remove(int index)

Ruby sort


arr = [3,4,1,0]
arr.sort!
# return [0,1,3,4]
puts arr

arr = [3,4,1,0]
newArr = arr.sort
# return [3,4,1,0]
puts arr

The first case is in house sort. (use sort!). The second case will not change the original list, but return a sorted new list. The only difference is !

No comments:

Post a Comment