简体   繁体   中英

How can I fix the toArray method in the end?

So earlier I asked a question on how to use boolean values to access the different end of my stack. So I fixed this :)

Were I am stuck now is at the end; I dont know how to implement the toArray method from the interface...ant comments or hints on how to fix it? #noob

I posted my boolean the push method for @NoStupidQuestions :D

public class TwoStackArray<E> implements Twostack<E> {

    // lots of code emitted...

    @Override
    public void push(Boolean right, E element) throws TwostackFullException {
        if (numberOfElement == size - 1) {
            throw new TwostackFullException("Stack overflow");
        }

        if (right) {
            arr[rightIndex] = element;
            rightIndex--;
        } else {
            arr[leftIndex] = element;
            leftIndex++;
        }

        numberOfElement++;
    }

    // lots of code emitted......................

    @Override
    public <T> T[] toArray(T[] a) {
        for (int i = 0; i < numberOfElement; i++) {
            System.out.println(arr[i]);
        }
    }

}

IJ tells me the last method lacks return...but I just guessed a for loop/print method here...not sure how to solve this

You have 2 options here:

  1. Return the array, you put in at first by changing your function toArray to this:
@Override
public <T> T[] toArray(T[] a) {
    for (int i = 0; i < a.length; i++) {
        System.out.println(a[i]);
    }
    return a;
}
  1. You can just change the return type to void:
@Override
public void toArray(Object[] a) {
    for (int i = 0; i < a.length; i++) {
        System.out.println(a[i]);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM