如何可能在一个类中定义一个与之同类的 List 或类似的数据类型?

huangapple go评论65阅读模式
英文:

How is it possible to define a List, or similar data type. of the same class into a class?

问题

以下是翻译好的内容:

我无法理解类似这样的事情怎么可能,现在我在我收到的代码中有以下的结构:

public class DayhoursItem {

    @SerializedName("code")
    private String code;

    @SerializedName("name")
    private String name;

    @SerializedName("dayhours")
    private List<DayhoursItem> dayhours;

据我所知,要使用dayhours,你需要定义一个DayhoursItem,然后需要在其中定义一个DayHoursItem对象的列表,然后该对象需要再定义一个DayHoursItem对象的列表,依此类推。

代码虽然在运行,但我无法理解为什么,因此我想知道为什么会出现这种情况(它的行为方式是怎样的)。

英文:

I cannot understand how something like that is possible, right now I've an structure like the following in a code I've been passed:

public class DayhoursItem {

	@SerializedName(&quot;code&quot;)
	private String code;

	@SerializedName(&quot;name&quot;)
	private String name;

	@SerializedName(&quot;dayhours&quot;)
	private List&lt;DayhoursItem&gt; dayhours;

As far as I know in order to use dayhours, you would need to define a DayhoursItem that would need to define a list with a DayHoursItem object that would need to define a list with a DayHoursItem object... and so on.

The code is working but I cannot understand why, so I'd like to know how exactly that can be (how is the way it's behaving).

答案1

得分: 4

因为在Java中,任何引用仅仅是“标识”相应的对象。

这意味着:当您定义一个类并对其进行实例化时,所有的字段只是指向其他对象。每个对象在堆上有它自己的存储空间。

因此,dayhours字段只是简单地指向一个列表对象,该对象的存储空间在堆的其他位置。无论该列表是空的还是包含其他DayHourItem对象都无关紧要:总是只有一个“指针”从拥有它的DayHourItem指向该列表对象。

这里没有递归。在其他编程语言中,类似的结构很可能是非法的。

当然,当DayHourItem类的构造函数试图创建另一个 DayHourItem对象(以添加到那个列表中)时,就会产生递归,并且会很快耗尽内存。

因此,要点是:这种“自我引用”可能会创建问题,但这并不一定总是情况。

英文:

Simple: because any reference in java only "identifies" the corresponding object.

This means: when you define a class, and instantiate it, all your fields only point to these other objects. Each object has its own storage on the heap.

So that dayhours field simply points to a List object, that has its storage elsewhere in the heap. And it doesn't matter whether that list is empty, or contains other DayHourItem object: there is always only one "pointer" to that list object, from the owning DayHourItem.

There is no recursion here. In other languages, similar constructs might very well be illegal.

Of course, when say the constructor of the DayHourItem class tries to create another DayHourItem object (to be added to that list), then you have a recursion, and you run out of memory quickly.

So the point is: such "self references" can create problem, but that isn't necessarily always the case.

huangapple
  • 本文由 发表于 2020年8月27日 20:02:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/63615552.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定