One simple question about clear() vs new ArrayList<Integer>()


  • 0
    L

    I met one confusing question about clear() and new ArrayList().

    Here is my original code:

    public List<List<Integer>> generate(int numRows) {
    	List<Integer> array = new ArrayList<Integer>();
        List<List<Integer>> pascalTriangle = new ArrayList<List<Integer>>();
        List<Integer> previous;
        
        if (numRows == 0){
        	return pascalTriangle;
        }
        array.add(1);
        pascalTriangle.add(array);
        if (numRows == 1){
        	return pascalTriangle;
        }
        for (int i=2; i<=numRows; i++){
        	previous = array;
        	array.clear();
        	for (int count=1; count<=i; count++){
        		if (count==1 || count==i){
        			array.add(1);
        		}
        		else{
        			array.add(previous.get(count-2)+previous.get(count-1));
        		}
        	}
        	pascalTriangle.add(array);
        }
        return pascalTriangle;
    }
    

    It gives the error: Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
    Which happened in array.add(previous.get(count-2)+previous.get(count-1));

    But when I change the array.clear() to array = new ArrayList<Integer>(), that works!

    So I am wondering why this works but clear() does not.


  • 0
    M

    Both 'previous' and 'array' point to the same ArrayList object. If you clear the 'array', the 'previous' will also be cleared. That's, size of 'previous' is 0. So you need create a new ArrayList object for the new row.


  • 0
    L

    I got it ! Thank you very much. I can fix this problem now.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.