Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can you have a HashSet of objects of that class

Tags:

java

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;
    //....
}
like image 963
alwayscurious Avatar asked Jul 16 '17 08:07

alwayscurious


People also ask

Can HashSet have objects?

Objects that you insert in HashSet are not guaranteed to be inserted in the same order. Objects are inserted based on their hash code. NULL elements are allowed in HashSet. HashSet also implements Serializable and Cloneable interfaces.

What is the HashSet class in Java and how does it store elements?

HashSet extends AbstractSet and implements the Set interface. It creates a collection that uses a hash table for storage. A hash table stores information by using a mechanism called hashing. In hashing, the informational content of a key is used to determine a unique value, called its hash code.

What is the main purpose of HashSet?

HashSet is a class that extends AbstractSet and implements the Set interface in Java. It is a very useful tool that allows you to store unique items and access them in constant time (on average). No duplicate values are stored.

Does HashSet allow heterogeneous objects?

In HashSet heterogeneous elements are allowed. HashSet allow “null” value. HashSet implements Serializable and Cloneable interface. In HashSet, searching objects is easier.


1 Answers

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;
}
like image 179
Eran Avatar answered Sep 22 '22 10:09

Eran