title: Indexing in java arrays
body: <p>I had to write a method in Java, where having in input an array <code>a</code> of numbers and a number <code>x</code> returns an array of elements which follows the last occurrence of <code>x</code> in <code>a</code>. </p>
  
  <p>For example with input <code>{0,1,2,3,4,5,6,7,8,9}</code> and <code>x=6</code> the method must return <code>{7,8,9}</code> meanwhile with <code>{4,1,4,2}</code> and <code>x=4</code> the method must return <code>{2}</code> and if the <code>x</code> is not in <code>a</code> then it must return empty array <code>{}</code> (or array with 0 length)</p>
  
  <p>so I got this answer:</p>
  
  <pre><code>int idx = -1;
  for (int i = 0; i &lt; s.length; i++) { 
      if (s[i] == x)
          idx = i;
  }
  
  /* After you found this index, create a new array starting 
   * from this element. It can be done with a second (not nested) for loop, or you can
   * use Arrays.copyOfRange()
   */
  
  //make sure idx != -1
  int[] t = new int[s.length - idx - 1];
  for (int i = idx + 1; i &lt; s.length; i++)
      t[i - idx - 1] = s[i];
  </code></pre>
  
  <p>which was very helpful but I could not understand why this works:(EDITED; Ok now I understand why this works but even if in my opinion the combined for loop ideea was more less complicated to read)</p>
  
  <pre><code>t[i - idx - 1] = s[i];
  </code></pre>
  
  <p>and this doesn't:</p>
  
  <pre><code>int[] t = new int[a.length - indx - 1];
  for (int j = indx + 1; j &lt; a.length; j++) {
      for (int i = 0; i &lt; t.length; i++) {
          t[i]=a[j];
      }
  }
  return t;
  </code></pre>
  
  <p>EDITED :
  To clarify this is all the code </p>
  
  <pre><code>int[] dopoX(int[] a, int x) {
      int n = a.length;
      int[] c = new int[0];
      int indx = 0;
      int nrx = 0;
      for (int j = 0; j &lt; a.length; j++) {
          if (a[j] == x)
              nrx++;
          if (a[j] == x)
              indx=j;
      }
      if (nrx == 0)
          return c;   
      int[] t = new int[n - indx - 1];
      for (int j = indx + 1; j &lt; n; j++) {
          for (int i = 0; i &lt; t.length; i++) {
              t[i] = a[j]; /* it returns just 1 number of a[] like t{2,2,2,2,2,2,2,2} which is 
                              not correct */          
          }
      }
      return t;
  }
  </code></pre>