0

I am getting error "Line 12:variable sblst is already defined in method generate(int)" for below code. I tried to modify below code and I dont get error when I declare the second and third list with a different name. I am new to java and not understanding what is happening here. My question is , in while loop the list is getting declared multiple times but am not getting error for the same.

class Solution {
    public List<List<Integer>> generate(int numRows) {

    if(numRows==0) return new ArrayList<List<Integer>>(0);

    List<List<Integer>> lst = new ArrayList<List<Integer>>();  //check list
    List<Integer> sblst = new ArrayList<Integer>(); 


    if(numRows>=1) sblst.add(1); lst.add(sblst);          //i=0
    if(numRows==1) return lst;
    List<Integer> sblst = new ArrayList<Integer>(); 
    if(numRows>=2) sblst.add(1); sblst.add(1); lst.add(sblst);            //i=1
    if(numRows==2)   return lst;

    int i=2;

    while(i<numRows){

    List<Integer> sblst = new ArrayList<Integer>(0); 
    sblst.add(1);
    int j=1;
    while(j<i){    
    int element = lst.get(i-1).get(j-1)+lst.get(i-1).get(j) ;
    sblst.add(element);
    j++;
    }
    sblst.add(1);
    lst.add(sblst);
    i++;
    }

    return lst;
    }
    }
1

1 Answer 1

1

In a single method, you delare sblst twice:

List<Integer> sblst = new ArrayList<Integer>(0); 

If you do need two lists, you should rename one of them.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks :) i declared second and third sblst as 'sblst1' and 'sblst2' , keeping name of 'sblst' in while loop same. Now the code runs fine, but my question is why is it not showing same error since list 'sblst' (of same name) is getting declared multiple times in the while loop while executing.
You are kind of thinking about the code as if it was an interpreted language. But Java is a compiled language. The compiler only sees one variable in the source code, it doesn't care that there are multiple "instances" of the variable in a loop. That is allowed by the Java language specification because it does not cause ambiguity.
Thanks .. i also think , i am a bit confused in the execution sequence of this Java code. Could you share some references(readings) where i could clear my confusions :)
@RobinGreen i read in stackoverflow that the memory of sblst is cleared after every iteration of loop..thats why it stores everytime in a different sblst....please clarify. stackoverflow.com/questions/19463138/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.