title: Why do I get a "duplicate local variable" error?
body: <p>I have a loop in which I calculate a value and add it it a list. So, I do something like that:</p>
  
  <pre><code>x = getValue()
  values.add(x)
  while (true) {
     x = getValue();
     values.add(x)
  }
  </code></pre>
  
  <p>I found out that this approach does not work since I add the same instance to the list. In more details, in every cycle of the loop I re-assign a new value to the <code>x</code> and doing so I change values of all elements that were already added to the list (so in the end I get a list of identical elements).</p>
  
  <p>To solve this problem I did the following:</p>
  
  <pre><code>x = getValue();
  Integer[] valueToAdd = new Integer[n];
  for (int i=0; i&lt;n; i++) {
     valueToAdd[i] = x[i];
  }
  while (true) {
     x = getValue();
     y = new Integer[n];
     for (int i=0; i&lt;n; i++) {
        valueToAdd[i] = x[i];
     }
     values.add(valueToAdd)
  }
  </code></pre>
  
  <p>In this way I wanted to create a new instance every time want to add a value to the list. But it does not work since I get a duplicate local variable error.</p>
  
  <p>It is also strange to me that I do not have this error if I declare the same variable many times in the loop. The problem appears only if I first declare a new variable outside the loop and then also in the loop.</p>
  
  <p>Is there a way in Java to re-use the same name for different instances?</p>
  
  <p><strong>ADDED</strong>
  I need to clarify some issues. I did not show all the code. I have the <code>break</code> command in the loop (when a new value cannot be generate, I exit the loop). <code>x</code> and <code>value</code> have <code>Integer[]</code> type.</p>
  
  <p><strong>ADDED 2</strong>
  Since it was mentioned that the problem can be in the <code>getValue()</code> I need to in more details here. Actually I do not have <code>getValue()</code> in my code (I used <code>getValue()</code> here to make my example shorter). In my code I had:</p>
  
  <pre><code>   Integer[] x = new x[n];
      while (true) {
         for (int i=0; i&lt;n; i++) {
            x[i] = y[i];
         }
         values.add(x)
      }
  </code></pre>
  
  <p>And it did not work since in my <code>values</code> list I had identical elements (and I know that in the loop on every cycle <code>x</code> had a new value).</p>
  
  <p><strong>ADDED 3</strong></p>
  
  <p><a href="https://stackoverflow.com/questions/4324754/why-all-elements-of-my-list-seems-to-be-the-same">Why all elements of my list seems to be the same?</a></p>