Reputation: 147
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("code")
private String code;
@SerializedName("name")
private String name;
@SerializedName("dayhours")
private List<DayhoursItem> 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).
Upvotes: 1
Views: 68
Reputation: 140427
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.
Upvotes: 4