首页 > 解决方案 > 最后如何修复 toArray 方法?

问题描述

所以早些时候我问了一个关于如何使用布尔值访问堆栈的不同端的问题。所以我修复了这个:)

我现在被卡住了吗?我不知道如何从接口实现 toArray 方法...关于如何修复它的评论或提示?#小白

我发布了@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 告诉我最后一个方法没有返回……但我只是在这里猜到了一个 for 循环/打印方法……不知道如何解决这个问题

标签: javastacktoarray

解决方案


您在这里有 2 个选项:

  1. 返回数组,首先通过将函数 toArray 更改为:
@Override
public <T> T[] toArray(T[] a) {
    for (int i = 0; i < a.length; i++) {
        System.out.println(a[i]);
    }
    return a;
}
  1. 您可以将返回类型更改为 void:
@Override
public void toArray(Object[] a) {
    for (int i = 0; i < a.length; i++) {
        System.out.println(a[i]);
    }
}

推荐阅读