【问题标题】:Generic Constructor Issues in Stack Array Implementation?堆栈数组实现中的通用构造函数问题?
【发布时间】:2015-02-28 22:38:19
【问题描述】:

我正在使用 Java 进行通用堆栈实现,但在构造函数方面遇到了一些问题。 Stack226Array 类实现了给我们的 Stack226。所以,我的构造函数声明如下:

public void Stack226Array(int initialCapacity) {
    this.stack = (T[]) new Object[initialCapacity];
    this.top = 0;
}

我这样称呼它:

Stack226<Integer> intStack = new Stack226Array<>(10);

返回错误:

 constructor Stack226Array in class Stack226Array<T> cannot be applied to given types;
Stack226<Integer> intStack = Stack226Array<Integer>(10);
required: no arguments
found: int

可能相关的问题,但是当我尝试将默认构造函数声明为:

public void Stack226Array() {
    this(100);
}

它返回一个错误,对 this 的调用必须是构造函数中的第一个语句。非常感谢任何可以提供帮助的人!如果您需要更多代码 sn-ps,请告诉我。

【问题讨论】:

  • 您的默认构造函数的返回类型为 void。构造函数没有返回类型!而且您之前的代码有语法错误,您应该发布正确的代码以供人们帮助。请更正第一行(this.stack...)因为这似乎很重要

标签: java generics constructor stack


【解决方案1】:

你的两个构造函数的问题是你把返回类型设置为 void。构造函数不能有返回类型。这就是为什么没有找到构造函数并且编译器认为只有一个默认构造函数的原因。

【讨论】:

    猜你喜欢
    • 2015-06-16
    • 2014-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-29
    • 2011-03-05
    • 2013-04-14
    相关资源
    最近更新 更多