gpt4 book ai didi

java - 为什么我们有时需要在静态方法声明中使用

转载 作者:行者123 更新时间:2023-12-02 08:10:47 25 4
gpt4 key购买 nike

对于以下方法,我收到以下错误“无法对非静态类型 E 进行静态引用”:

public static void reverse(E[] a) {
Stack<E> buffer = new Lab8<>(a.length);

for (int i=0; i < a.length; i++)
buffer.push(a[i]);

for (int i=0; i < a.length; i++)
a[i] = buffer.pop();
}

现在我知道执行以下操作将修复错误,但我不明白 的意义(为什么我们在这种情况下需要它),并且在方法中定义它没有意义像那样?我确实知道如何使用它来声明泛型类和实例,但这是我第一次看到它以这种方式使用...

public static <E> void reverse(E[] a) {
Stack<E> buffer = new Lab8<>(a.length);

for (int i=0; i < a.length; i++)
buffer.push(a[i]);

for (int i=0; i < a.length; i++)
a[i] = buffer.pop();
}

这是完整的引用代码:

 package labs;

import java.util.Arrays;

public class Lab8<E> implements Stack<E> {

public static final int CAPACITY=1000;
private E[] data;
private int t = -1;
public Lab8() { this(CAPACITY); }
public Lab8(int capacity) {
// default array capacity
// generic array used for storage
// index of the top element in stack
// constructs stack with default capacity // constructs stack with given capacity // safe cast; compiler may give warning
data = (E[ ]) new Object[capacity];

}
public int size() { return (t + 1); }
public boolean isEmpty() { return (t == -1); }
public void push(E e) throws IllegalStateException {
if (size() == data.length) throw new IllegalStateException("Stack is full");
data[++t] = e;
}

public E top() {
if (isEmpty()) return null;
return data[t];
}

public E pop() {
if (isEmpty( )) return null;
E answer = data[t];
data[t] = null;
t--;
return answer;
}

public static void reverse(E[] a) {
Stack<E> buffer = new Lab8<>(a.length);

for (int i=0; i < a.length; i++)
buffer.push(a[i]);

for (int i=0; i < a.length; i++)
a[i] = buffer.pop();
}

public static void main(String[] args) {
Integer[] a = {4, 8, 15, 16, 23, 42}; // autoboxing allows this
String[] s = {"maryam", "ricardo", "Mostafa", "Ahmend", "Hitler"};
System.out.println("a = " + Arrays.toString(a));
System.out.println("s = " + Arrays.toString(s));
System.out.println("Reversing...");
reverse(a);
reverse(s);
System.out.println("a = " + Arrays.toString(a)); System.out.println("s = " + Arrays.toString(s));
}
}

最佳答案

如果你不把那个 <E>在方法声明中,编译器将无法理解你是想创建一个泛型方法,还是试图引用一个名为 E 的实际类并且只是忘记导入它。在没有类型参数的情况下,编译器只能假设第二个选项并提示,因为它找不到 E随时随地上课。

关于java - 为什么我们有时需要在静态方法声明中使用 <E>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47241002/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com