How to create tree in java

What is a Binary Tree in Java? | Advantages

Binary Tree in Java is a renowned type of data structure where data or objects are arranged in a non-linear hierarchical structure, and every item is called as a ‘node’ while all the nodes are connected to the starting point called the root node. The placement of the data or objects is made so that the value of every left side node is low or equal to the root node, and the value of every right-side node is high or equal to the root node. Any given binary tree should have at least one root node, and the parent nodes can have a maximum of two child nodes in every level of the hierarchical tree.

Understanding Binary Tree in Java

BST(Binary Search Tree) is a well-known data structure that is required to retain parts in sequence. Every binary search tree is a binary tree in which the valuation of a left side child node is lower or equivalent to the parent node, and the valuation of the right child is larger than or equivalent to the parent node.

How does Binary Tree in Java make working so easy?

Binary Tree in Java makes working so easy as they are utilized to execute binary search trees and binary heaps, attaining applications in sorting algorithms and effective searching.

What can you do with Binary Tree in Java?

With the Binary tree in Java with the children, nodes are parent nodes and might hold mentions to their parent nodes. From the exterior of the binary tree, there is usually a root node reference as every node’s ancestor in case it is in existence. Every node is the information structure that could be approached by beginning at the root’s node and recurringly ensuing references to rather to the left child or right child. The binary tree cannot have any node, or it might consist of a root node specified to as a null tree. The maximum parent nodes can have about two child nodes in each binary tree.


Considering it is a binary tree, it could just have zero child node or one child node or two children. The binary search tree speciality is its capability to lessen the time complication of basic processes such as remove, search and add, including identified as to find, insert, and delete. Every operation such as remove, find and insert can be carried out by binary search tree on time. The basis for the enhancements in speed is due to the unique attribute of the binary search tree for every node, the information in the left side child is lower than or equivalent, and the information in the right child is more than or equivalent to the information in the said node.

Why should we use Binary Tree in Java?

The structure of tree data is beneficial on moments when a linear representation of information is not enough, just like building a family tree. There are two inbuilt categories in Java: TreeMap and TreeSet, under Java Framework Collection that serve the programmer’s requirements to specify data components in the above-mentioned form.


As previously mentioned, that Java framework collection consists of two variations of tree executions; one of them is TreeSet, and the other is TreeMap. The fascinating characteristics of both the above-mentioned three categories are that one of them is equipped as a Set and another one as Map. The interfaces of Map and Set were executed through abstract categories such as AbstractMap and AbstractSet.

How does a binary tree work?

The attributes it enforces at the time of the compilation of the components are established on the abstraction model’s analytical set. The attribute of Map enforces the compilation of components should have a key valuation pair. Every key outline to just 1 value which implies it rejects duplicate keys.  Each value has a different key that can be replicated. TreeSet and TreeMap are the two categories of binary trees that comply with the particular standards obtained from their particular interfaces aside from organizing its data structure internally in a binary tree pattern.

Why do we need a Binary Tree in Java?

The binary tree with its many categories is unique because it is easy and effective to execute. The limitations with the binary trees are that it enables at least two nodes children under a parent node as they are known as right side child or left side child accordingly. The binary tree advancing from the right side child is known as the right sub tree, and advancing from the left side child is known as a left-sub tree. This is usually for every binary tree due to a binary tree with several execution schemes. These schemes have definitely distinct established standards for building and maintenance, which immediately affects the access of the data components norms generally estimated in the notion of Big O.

Career Growth

Software and SaaS solutions can be created with the implementation of Binary Tree to facilitate the enterprises in every location to modify and lead to future technology. The programmers can advance their career by learning this binary tree and explore the scope to create more utilization.


The TreeMap and TreeSet are usually the clearest execution of binary tree data structure in the library of JavaAPI. As the data laws, the structure does not obtain any distinction in its utilization for high-grade users. However, the tree structure is somewhat more complex and ineffective than linear or non-tree counterparts, such as HashMap and HashSet, because of its several rules to preserve a balanced tree structure’s standards.

Recommended Articles

This has been a guide to What is a binary tree in Java. Here we discuss the Advantages, Scope, and career growth of a binary tree in java. You may also look at the following articles to learn more –

  1. What is XML?
  2. What is Bootstrap?
  3. What is a Hive?
  4. What is Ansible?

Java Trees, Java JTree Example, Create Tree in Java, Creating a JTree Component


In this section, you will learn about the JTree and its components as well as how to create an JTree component. Here, first of all we are going to describe about the JTree and its component. The java.swing  package provides the JTree and its component. 

JTree: The tree is a special type of graph that designed for displaying data with the hierarchical properties by adding nodes to nodes and keeps the concept of parent and child node.

Node: A node is an object at any position within the JTree where the data are associated or being represented. 

Path: The path is the collection of contiguous set of nodes that contains one or many nodes. The path is empty or null when the path has not any node.

Leaf: This is a special types of node at the end of a path. The leaf node has not connected to more nodes.

Root: This is the node of highest point within the hierarchy in tree. 

Parent:  It represents the relationship of node with another node. In object-oriented programming concepts the parent is a super class.

Child: It represents the relationship of node with another node. In object-oriented programming concepts the child is a subclass of its parent. It inherits all properties of its parent.

Description of program:

The following program creates the simple JTree component. The tree is a special type of graph that build the tree hierarchy by adding nodes to nodes and keeps the concept of parent and child node or root and a child of root node. Whenever you will go to create a tree, you will need root node that will be created by the DefaultMutableTreeNode() method. All objects of DefaultMutableTreeNode are added in the specifying parent or child nodes that will be specified by you and root node are added in the JTree object that will also added on the frame.

Description of code:

DefaultMutableTreeNode("Color", true):
This is the constructor of DefaultMutableTreeNode class. It creates a tree node with no root node, the child of root node, specified by user object and it allows only children that have to be specified. It takes boolean types values either 'true' or 'false'. If you will take 'true' that means children node are allowed otherwise  it will display the IllegalStateException

JTree(TreeNode parent):
This is the constructor of JTree class that shows a set of hierarchical data. It returns a JTree with given TreeNode that displays the root node in a tree. By default, the tree defines the leaf  node of a tree. It takes the following types of arguments:

    parent:  This is the name of an object of TreeNode that displays the root node. 

Here is the code of program:

import javax. swing.*;
import javax.swing.tree.*;

public class TreeComponent{
public static void main(String[] args) {
JFrame frame = new JFrame("Creating a JTree Component!");
DefaultMutableTreeNode parent = new DefaultMutableTreeNode("Color", true);
DefaultMutableTreeNode black = new DefaultMutableTreeNode("Black");
DefaultMutableTreeNode blue = new DefaultMutableTreeNode("Blue");
DefaultMutableTreeNode nBlue = new DefaultMutableTreeNode("Navy Blue");
DefaultMutableTreeNode dBlue = new DefaultMutableTreeNode("Dark Blue");
DefaultMutableTreeNode green = new DefaultMutableTreeNode("Green");
DefaultMutableTreeNode white = new DefaultMutableTreeNode("White");
parent.add(green );
JTree tree = new JTree(parent);
frame.setDefaultCloseOperation(JFrame. EXIT_ON_CLOSE);

Download this example.

Output of program:

How can I implement a tree in Python? Are there built-in data structures in Python like there are in Java? En Python

I'm trying to build a generic tree. Are there built-in data structures in Python to implement a tree?

Python does not have a fairly wide range of "built-in" data structures, as Java does. However, since Python is dynamic, a shared tree is easy to create. For example, a binary tree might be:

 class Tree(object): def __init__(self): self.left = None self.right = None = None 

You can use it like this:

 root = Tree() root. data = "root" root.left = Tree() = "left" root.right = Tree() root.right. data = "right" 

I recommend


 from anytree import Node, RenderTree udo = Node("Udo") marc = Node("Marc", parent =udo) lian = Node("Lian", parent=marc) dan = Node("Dan", parent=udo) jet = Node("Jet", parent=dan) jan = Node("Jan", parent=dan ) joe = Node("Joe", parent=dan) print(udo) Node('/Udo') print(joe) Node('/Udo/Dan/Joe') for pre, fill, node in RenderTree(udo) : print("%s%s" % (pre, Udo ├── Marc │ └── Lian └── Dan ├── Jet ├── Jan └── Joe print(dan.children) (Node('/Udo/Dan/Jet'), Node('/Udo/Dan/Jan'), Node('/Udo/Dan/Joe')) 


anytree also has a powerful API:

  • easy tree creation
  • simple wood modification
  • pre-order tree iteration
  • tree iteration after order
  • allow relative and absolute node paths
  • going from one node to another.
  • tree rendering (see example above)
  • connecting/disconnecting units

A general tree is a node with zero or more children, each of which is a regular (tree). This is not the same as a binary tree, they are different data structures, although both share some terminology.

Python does not have a built-in data structure for generic trees, but it is easily implemented using classes.

 class Tree(object): "Generic tree node." def __init__(self, name='root', children=None): = name self.children = [] if children is not None: for child in children: self.add_child(child) def __repr__(self): return def add_child(self, node): assert isinstance(node, Tree) self.children.append(node) # * # /|\ # 1 2 + # / \ # 3 4 t = Tree('*' , [Tree('1'), Tree('2'), Tree('+', [Tree('3'), Tree('4')])]) 

You can try:

 from collections import defaultdict def tree(): return defaultdict(tree) users = tree() users['harold']['username'] = 'hrldcpr' users['handler']['username '] = 'matthandlersux' 

As suggested here: https://gist.

There are no trees inside, but you can easily build them by subclassing the node type from a list and writing traversal methods. If you do this, I found bisect useful.

There are also many PyPi implementations you can browse.

If I remember correctly, the Python standard library does not include tree data structures for the same reason that the .NET base class library does: memory locality decreases, resulting in more cache misses. On modern processors, it's generally faster to just bring a large chunk of memory into the cache, and pointer-rich data structures negate the benefit.

 class Node: """ Class Node """ def __init__(self, value): self.left = None = value self.right = None class Tree: """ Class tree will provide a tree as well as utility functions. """ def createNode(self, data): """ Utility function to create a node. """ return Node(data) def insert(self, node , data): """ Insert function will insert a node into tree. Duplicate keys are not allowed. """ #if tree is empty , return a root node if node is None: return self.createNode(data) # if data is smaller than parent , insert it into left side if data < node.left = self.insert(node.left, data) elif data > node.right = self.insert(node.right, data) return node def search(self, node, data): """ Search function will search a node into tree. """ # if root is None or root is the search data. if node is None or == data: return node if < data: return, data) else: return, data) def deleteNode(self, node,data): """ Delete function will delete a node into tree. Not complete , may need some more scenarion that we can handle Now it is handling only leaf. """ # Check if tree is empty. if node is None: return None # searching key into BST. if data < node.left = self.deleteNode(node.left, data) elif data > node.right = self.deleteNode(node.right, data) else: # reach to the node that need to delete from BST. if node.left is None and node.right is None: del node if node.left == None: temp = node.right del node return temp elif node.right == None: temp = node.left del node return temp return node def traverseInorder(self, root): """ traverse function will print all the node in the tree. """ if root is not None: self.traverseInorder(root.left) print self.traverseInorder(root. right) def traversePreorder(self, root): """ traverse function will print all the node in the tree. """ if root is not None: print self.traversePreorder(root.left) self.traversePreorder(root .right) def traversePostorder(self, root): """ traverse function will print all the node in the tree. """ if root is not None: self.traversePreorder(root.left) self.traversePreorder(root.right) print def main(): root = None tree = Tree() root = tree.insert(root, 10) print root tree.insert(root, 20) tree.insert(root, 30) tree.insert(root , 40) tree.insert(root, 70) tree.insert(root, 60) tree.insert(root, 80) print "Traverse Inorder" tree. traverseInorder(root) print "Traverse Preorder" tree.traversePreorder(root) print "Traverse Postorder" tree.traversePostorder(root) if __name__ == "__main__": main() 

I have implemented the root tree as a dictionary {child:parent} . So, for example, with the root node 0 , the tree might look like this:

 tree={1:0, 2:0, 3:1, 4:2, 5:3} 

from any node to the root, which was relevant for the problem I was working on.

I have implemented trees using nested dicts. This is pretty easy to do and has worked for me with fairly large datasets. I have posted a sample below and you can see more in google code

 def addBallotToTree(self, tree, ballotIndex, ballot=""): """Add one ballot to the tree. The root of the tree is a dictionary that has as keys the indicies of all continuing and winning candidates. For each candidate, the value is also a dictionary, and the keys of that dictionary include "n" and "bi". tree[c]["n"] is the number of ballots that rank candidate c first. tree[c][" bi"] is a list of ballot indices where the ballots rank c first. If candidate c is a winning candidate, then that portion of the tree is expanded to indicate the breakdown of the subsequently ranked candidates. In this situation, additional keys are added to the tree[c] dictionary corresponding to subsequently ranked candidates. tree[c]["n"] is the number of ballots that rank candidate c first. tree[c]["bi"] is a list of ballot indices where the tree[c][d]["n"] is the number of ballots that rank c first and d second.tree[c][d]["bi"] is a list of the corresponding ballot indices . Where the second ranked candidates is also a winner, then the tree is expanded to the next level. Losing candidates are ignored and treated as if they do not appear on the ballots. For example, tree[c][d]["n"] is the total number of ballots where candidate c is the first non-losing candidate, c is a winner, and d is the next non-losing candidate. This will include the following ballots, where x represents a losing candidate: [cd] [xcd] [cxd] [xcxxd] During the count, the tree is dynamically updated as candidates change their status. The parameter "tree" to this method may be the root of the tree or may be a sub-tree. """ if ballot == "": # Add the complete ballot to the tree weight, ballot = self.b.getWeightedBallot(ballotIndex) else: # When ballot is not "", we are adding a truncated ballot to the tree, # because a higher-ranked candidate is a winner.weight = self.b.getWeight(ballotIndex) # Get the top choice among candidates still in the running # Note that we can't use Ballots.getTopChoiceFromWeightedBallot since # we are looking for the for c in ballot: if c in self.continuing | break # c is the top choice so stop else: c = None # no candidates left on this ballot if c is None: # This will happen if the ballot contains only winning and losing # candidates.The ballot index will not need to be transferred # again so it can be thrown away.return # Create space if necessary.if not tree.has_key(c): tree[ c] = {} tree[c]["n"] = 0 tree[c]["bi"] = [] tree[c]["n"] += weight if c in # Because candidate is a winner, a portion of the ballot goes to # the next candidate. Pass on a truncated ballot so that the same # candidate doesn't get counted twice. i = ballot.index(c) ballot2 = ballot[i+1:] self.addBallotToTree(tree[c], ballotIndex, ballot2) else: # Candidate is in continuing so we stop here. tree[c]["bi"].append(ballotIndex) 

Greg Hugill's answer is great, but if you need more nodes per level, you can use a list to create them. And then use a method to access them by name or order (like id)

 class node(object): def __init__(self): self.node=[] self.otherInfo = None self.prev =None def nex(self,child): "Gets a node by number" return self.node[child] def prev(self): return self.prev def goto(self,data): "Gets the node by name" for child in range(0,len(self.node)): if(self.node[child].name==data): return self.node[child] def add(self): node1=node() self.node .append(node1) node1.prev=self return node1 

Now just create a root and create it: ex:

 tree=node() #create a node"root" #name it root tree. otherInfo="blue" #or what ever tree=tree.add () #add a node to the root"node1" #name it root / child1 tree=tree.add()"grandchild1" root / child1 / grandchild1 tree=tree.prev() tree= tree.add()"gchild2" root / child1 / \ grandchild1 gchild2 tree=tree.prev() tree=tree.prev() tree=tree.add()"child2" root / \ child1 child2 / \ grandchild1 gchild2 tree=tree.prev() tree=tree.goto("child1") or tree=tree.nex(0)"changed" root / \ changed child2 / \ grandchild1 gchild2 

This should be enough to get you started figuring out how to make this work

I have published a Python tree implementation [3] on my website: .

Hope this is helpful,

Ok, here is the code:

 import uuid def sanitize_id(id): return id.strip().replace(" ", "") (_ADD, _DELETE, _INSERT) = range( 3) (_ROOT, _DEPTH, _WIDTH) = range(3) class Node: def __init__(self, name, identifier=None, expanded=True): self. __identifier = (str(uuid.uuid1()) if identifier is None else sanitize_id(str(identifier))) = name self.expanded = expanded self.__bpointer = None self.__fpointer = [] @property def identifier(self): return self.__identifier @property def bpointer(self): return self.__bpointer @bpointer.setter def bpointer(self, value): if value is not None: self.__bpointer = sanitize_id(value) @property def fpointer(self): return self.__fpointer def update_fpointer(self, identifier, mode =_ADD): if mode is _ADD: self.__fpointer.append(sanitize_id(identifier)) elif mode is _DELETE: self.__fpointer.remove(sanitize_id(identifier)) elif mode is _INSERT: self.__fpointer = [sanitize_id(identifier) ] class s Tree: def __init__(self): self.nodes = [] def get_index(self, position): for index, node in enumerate(self.nodes): if node.identifier == position: break return index def create_node(self , name, identifier=None, parent=None): node = Node(name, identifier) ​​self.nodes.append(node) self.__update_fpointer(parent, node. identifier, _ADD) node.bpointer = parent return node def show( self, position, level=_ROOT): queue = self[position].fpointer if level == _ROOT: print("{0} [{1}]".format(self[position].name, self[position]. identifier)) else: print("\t"*level, "{0} [{1}]".format(self[position].name, self[position].identifier)) if self[position].expanded: level += 1 for element in queue:, level) # recursive call def expand_tree(self, position, mode=_DEPTH): # Python generator. Loosly based on an algorithm from 'Essential LISP' by # John R. Anderson, Albert T. Corbett, and Brian J. Reiser, page 239-241 yield position queue = self[position].fpointer while queue: yield queue[0] expansion = self[queue[0]].fpointer if mode is _DEPTH: queue = expansion + queue[1:] # depth-first elif mode is _WIDTH: queue = queue[1:] + expansion # width-first def is_branch(self, position): return self[position].fpointer def __update_fpointer(self, position, identifier, mode): if position is None: return else: self[position]. update_fpointer(identifier, mode) def __update_bpointer(self, position, identifier): self[position].bpointer = identifier def __getitem__(self, key): return self.nodes[self.get_index(key) ] def __setitem__(self, key, item): self.nodes[self.get_index(key)] = item def __len__(self): return len(self.nodes) def __contains__(self, identifier): return [node.identifier for node in self.nodes if node.identifier is identifier] if __name__ == "__main__": tree = Tree() tree.create_node("Harry", "harry") # root node tree.create_node("Jane", " jane", parent = "harry") tree.create_node("Bill", "bi ll", parent = "harry") tree.create_node("Joe", "joe", parent = "jane") tree.create_node("Diane", "diane", parent = "jane") tree.create_node(" George", "george", parent = "diane") tree.create_node("Mary", "mary", parent = "diane") tree.create_node("Jill", "jill", parent = "george") tree .create_node("Carol", "carol", parent = "jill") tree.create_node("Grace", "grace", parent = "bill") tree.create_node("Mark", "mark", parent = " jane") print("="*80) tree. show("harry") print("="*80) for node in tree.expand_tree("harry", mode=_WIDTH): print(node) print(" ="*80) 
 class Tree(dict): """A tree implementation using python's autovivification feature.""" def __missing__(self, key): value = self[key] = type(self)() return value #cast a (nested ) dict to a (nested) Tree class def __init__(self, data={}): for k, data in data.items(): if isinstance(data, dict): self[k] = type(self)(data ) else: self[k] = data 

works like a dictionary but provides as many nested dicts as you want. Try this:

 your_tree = Tree() your_tree['a']['1']['x'] = '@' your_tree['a']['1']['y'] = '#' your_tree['a']['2']['x'] = '$' your_tree['a']['3'] = '%' your_tree['b'] = '*' 

will supply a nested dict... that works like a tree.

 {'a': {'1': {'x': '@', 'y': '#'}, '2': {'x': '$'}, '3': '% '}, 'b': '*'} 

… If you already have a dict, it will cast every level to the tree:

 d = {'foo': {'amy': {'what': 'runs '} } } tree = Tree(d) print(d['foo']['amy']['what']) # returns 'runs' d['foo']['amy']['when'] = 'now' # add new branch 

So you can keep editing/adding/removing each signal level as you wish. All dict methods for traversal etc still apply.

What operations do you need? Python often has a good solution using a dict or a list with the bisect module.

PyPI has many tree implementations, and many types of trees are almost trivial to implement in pure Python. However, this is rarely necessary.

 def iterative_bfs(graph, start): '''iterative breadth first search from start''' bfs_tree = {start: {"parents":[], "children":[], "level":0}} q = [start] while q: current = q.pop(0) for v in graph[current]: if not v in bfs_tree: bfs_tree[v]={"parents":[current], "children":[], "level": bfs_tree[current]["level"] + 1} bfs_tree[current]["children"].append(v) q.append(v) else: if bfs_tree[v]["level"] > bfs_tree [current]["level"]: bfs_tree[current]["children"].append(v) bfs_tree[v]["parents"].append(current) 
  • matplotlib: how to change color of data points based on some variable
  • Function change list values, not variable values ​​in Python
  • Largest binary search tree value
  • Memory Efficient data structure to implement Trie
  • Deletion in a binary search tree with parent pointers
  • Construct a tree from a list of parent/child elements in Python
  • Tree matching algorithm?
  • How to generate a
    • tree without recursive use using python or another language?
    • How to iterate this tree/graph
    • Finding the minimum value in a binary tree, Python
    • Dynamic tree pruning

    Java | Collection types.

    Collection interface

    Last updated: 04/30/2018

    Arrays are designed to store data sets in Java. However, they are not always convenient to use, primarily because they have a fixed length. Collections solve this problem in Java. However, the point is not only in flexible in size sets of objects, but also in the fact that collection classes implement various algorithms. and data structures, such as stack, queue, tree, and a number of others.

    Collection classes are located in the package java.util , so you must include this package before using collections.

    Although there are many collections in Java, they all form a coherent and logical system. First, all collections are based on the use of one or another interface that defines the basic functionality. Among these interfaces are the following:

    • Collection: base interface for all collections and other collection interfaces

    • Queue: inherits the Collection interface and represents functionality for data structures as a queue

    • Deque: inherits the Queue interface and provides functionality for bidirectional queues

    • List: inherits the Collection interface and provides the functionality of simple lists

    • Set: also extends the Collection interface and is used to store sets of unique objects

    • SortedSet: extends the Set interface to create sorted collections

    • NavigableSet: Extends the SortedSet interface to create collections that can be searched by match

    • Map: designed to create data structures in the form of a dictionary, where each element has a specific key and value. Unlike other collection interfaces, it does not inherit from the Collection interface

    These interfaces are partially implemented by abstract classes:

  • AbstractList: extends the AbstractCollection class and uses the List interface, designed to create collections in the form of lists

  • AbstractSet: extends the AbstractCollection class and uses the Set interface to create collections as sets

  • AbstractQueue: extends the AbstractCollection class and uses the Queue interface, designed to create collections in the form of queues and stacks

  • AbstractSequentialList: Also extends the AbstractList class and implements the List interface. Used to create linked lists

  • AbstractMap: uses the Map interface, designed to create sets like a dictionary with objects in the form of a key-value pair

Using the above interfaces and abstract classes, Java implements a wide range of collection classes - lists, sets, queues, mappings, and others, among which are the following:

  • ArrayList: a simple list of objects

  • LinkedList: Represents a linked list

  • ArrayDeque: bidirectional queue class where we can insert and delete like at the beginning of a collection, so at its end

  • HashSet: a set of objects or a hash set, where each element has a key - a unique hash code

  • TreeSet: a set of sorted objects in the form of a tree

  • LinkedHashSet: linked hash set

  • PriorityQueue

  • HashMap: Dictionary data structure where each object has a unique key and some value

  • TreeMap: a tree-like data structure where each element has a unique key and some value

The whole collection system can be summarized schematically as follows:

Collection interface

The Collection interface is the base for all collections, defining the main functionality:

 public interface Collection extends Iterable{ // method definitions } 

The Collection interface is generic and extends the Iterable interface so that all collection objects can be iterated over by type for-each .

The methods of the Collection interface include the following:

  • boolean add (E item) : adds an item object to the collection. Returns true on successful addition, false on unsuccessful

  • boolean addAll(Collection col) : Adds all elements from the col collection to the collection. Returns true on successful addition, false on unsuccessful

  • void clear() : removes all elements from the collection

  • boolean contains (Object item) : returns true if item is contained in the collection, false otherwise

  • boolean isEmpty() : returns true if the collection is empty, otherwise returns false

  • Iterator iterator () : Returns an Iterator object to iterate over the elements of the collection

  • boolean remove (Object item) : returns true if item was successfully removed from the collection, false otherwise

  • boolean removeAll (Collection col) : Removes all objects in the collection col from the current collection. Returns true if the current collection has changed otherwise returns false

  • boolean retainAll (Collection col) : Removes all objects from the current collection except those contained in the col collection. If the current collection has changed after deletion, returns true, otherwise returns false

  • int size () : returns the number of elements in the collection

  • Object[] toArray () : returns an array containing all elements of the collection

All these and other methods that are available in the Collection interface are implemented by all collections, therefore, in general, the general principles of working with collections will be the same. The uniform interface makes it easy to understand and work with different types of collections. So, adding an element will be done using the add method, which takes the added element as a parameter. To remove, the method remove() is called.

Learn more