gpt4 book ai didi

java - 类中的类型 "place"是什么意思?

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:59:45 26 4
gpt4 key购买 nike

我正在阅读有关泛型类型的 Oracle 教程,第一段真的让我头疼。页面在这里https://docs.oracle.com/javase/tutorial/java/generics/types.html本教程从一个名为“Box”的类开始:

public class Box {
private Object object;

public void set(Object object) { this.object = object; }
public Object get() { return object; }
}

接下来的一段也是我一生都无法理解的一段,它写道:

Since its methods accept or return an Object, you are free to pass in whatever you want, provided that it is not one of the primitive types. There is no way to verify, at compile time, how the class is used. One part of the code may place an Integer in the box and expect to get Integers out of it, while another part of the code may mistakenly pass in a String, resulting in a runtime error.

最后一句话对我来说完全没有意义,我已经阅读了该特定页面的其余部分,但仍然无法准确理解他们想说的内容,感觉我错过了大部分内容课。将某物“放入”盒子中是什么意思?

我已经尝试了所有方法,我尝试以一千种不同的方式实例化 Box 类以使其有意义,它们都会导致编译时错误而不是运行时错误。无论我从哪个角度看,我都无法理解这一点,我很难理解这意味着什么

最佳答案

由于我们处于 Box 类的上下文中 - 一个物理盒子的抽象类 - “将”一个整数“放入”盒子只是一种抽象的方式说“设置object 字段到 Integer 的实例。

至于你的评论:

it seems like first they are saying I can pass anything, and then they're are saying I can't

这就是最后一句话的意思:你可能有这样的代码:

Box b = new Box();
b.set(1); // I've put an integer into the box, I should be able to get integers out of it later on

...

Integer i = (Integer)b.get();

本教程所指的“代码的另一部分”是“...”部分。如果“...”实际上有这样一行:

b.set("String"); // I forgot that I'm supposed to only put Integers in the box

然后最后一行会抛出异常。

泛型通过使 b.setObject("String"); 发出编译器错误来解决这个问题。

关于java - 类中的类型 "place"是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57836852/

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