0

I am trying to build a generic array but in reverse so for example if [2,3,4,5] was removed from the original array would return [5,4,3,2]. My issue is my code is not doing that. How do you do this with a generic? Here is my attempt.

public E[] removeNItems(int n) {
    E[] a = newArray(n);

    if (n > size) {
        return null;
    } else {
        size=size-n;
        int j=0;
        for (int i = size; i <= n; i++) {

            a[j] = stack[i];

            stack[i] = null;
            j++;


        }

    }


    return a;

}
Eric Smith
  • 51
  • 1
  • 9
  • If reversing the array is the only problem you have, then the duplicate link should have you covered. If you have other generics problems, then let us know. – Tim Biegeleisen Oct 19 '17 at 03:55
  • @TimBiegeleisen I know how to do this with a regular array but not with a generic. – Eric Smith Oct 19 '17 at 03:56
  • What errors do you get, and why is your method called `removeNItems()` ? – Tim Biegeleisen Oct 19 '17 at 03:57
  • @TimBiegeleisen the method is called that because it is removing items from a stack. The return array is what was removed but in reverse order. The only error I am getting is in my output the array is not in reverse order. – Eric Smith Oct 19 '17 at 04:00
  • just replace `a[j] = stack[i];` with `a[n-1-j] = stack[i];` – Lino Oct 19 '17 at 07:52

0 Answers0