Why do you have HashSet objects of this class?

I am afraid to understand why this is possible. I am new to java and don't understand how you can have a collection of any type (lists or sets) of type Example. I struggle to understand both the recursive nature of this and why it is used.

class Example { private Set<Example> setExample; //.... } 
+7
java
source share
3 answers

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

As for why this is used, objects in real life can (and often) be connected to other objects of the same type. A person is associated with other persons (members of their families), a web page may link to other related web pages, etc.

A common application of such links in data structures is Nodes / Links, which are used to implement linked lists and trees. Each Node / Link contains some data, in addition to links to one or more other nodes / links associated with the current Node / Link.

 class TreeNode<T> { T data; private List<TreeNode<T>> children; } 
+9
source share

This is possible because a variable of type Example is just a reference to an object of this type. Java is trying to hide what other languages ​​call pointers.

+3
source share

The question is if this is possible or independent of the rest of your code. for example

 class Example { private Set<Example> setExample; public Example() { setExample = new HashSet<Example>(); } 

Creates a new empty container that can contain Example objects. There is no problem with this. but

 class Example { private Set<Example> setExample; public Example() { setExample = new HashSet<Example>(); setExample.add(new Example()); } 

Creates an infinite loop type, and you get an OutOfMemoryError , since each instance of Example will create another instance of Example and so on. However, this is not recursion.

+3
source share

All Articles