gpt4 book ai didi

java - 泛型 - 为什么类类型变量在静态上下文中无效?

转载 作者:行者123 更新时间:2023-12-01 07:43:19 24 4
gpt4 key购买 nike

我正在从一本书中学习Java泛型。书上说“类类型变量在静态上下文中无效”,并用下面的例子进行了解释。

考虑一个具有类型变量的泛型类,例如 Entry。不能将类型变量 K 和 V 与静态变量或方法一起使用。例如,以下内容不起作用:

public class Entry<K, V> {
// Compiler error - V in static context ("Entry.this' cannot be referenced from a static context")
private static V defaultValue;

// Compiler error - V in static context ("Entry.this' cannot be referenced from a static context")
public static void setDefault(V value) {
defaultValue = value;
}
}

毕竟,类型删除意味着删除的 Entry 类中只有一个这样的变量或方法,而不是每个 K 和 V 都有一个这样的变量或方法。

我不明白上面的解释。我也尝试为 K 创建相同的代码,但得到了相同的编译错误。为什么上面的代码是非法的?

最佳答案

假设 static变量确实按照您描述的方式工作...

我本来能够做到:

Entry<String, Integer>.defaultValue = 1;
Entry<String, String>.defaultValue = "Hello";
System.out.println(Entry<String, Integer>.defaultValue); // 1
System.out.println(Entry<String, String>.defaultValue); // Hello

这正是您所期望的,不是吗?

但请记住static变量每个类一个。由于类型删除,Entry<String, Integer>Entry<String, String>被视为同一类。对于上面的代码,1"Hello"需要存储在两个不同的地方(两个变量)!

关于java - 泛型 - 为什么类类型变量在静态上下文中无效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61018031/

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