Why can you have a HashSet of objects of that class

alwayscurious :

I'm battling to understand why this is possible. I'm a java newbie and don't understand how you can have a collection of any type (lists or sets) be of type Example. I'm battling to understand both the recursive nature of this as well as why this is used.

class Example {
    private Set<Example> setExample;
    //....
}
Eran :

An object can contain references to other objects of the same class. It can even contain a reference to itself (though that may cause problems in some cases).

As to why this is used - objects in real life can (and often are) be related to other objects of the same type. A person is related to other persons (their family members), a web page can refer to other web pages related to it, etc...

A common usage of such references in data structures are Nodes/Links, which are used to implement linked lists and trees. Each Node/Link holds some data, in addition to a reference to one or more other Nodes/Links related to the current Node/Link.

class TreeNode<T> {
    T data;
    private List<TreeNode<T>> children;
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=459355&siteId=1