Sunday, 1 November 2015

How to add elements in HashSet



When you need to add elements to a set, you can either add a single element or a group of elements.
              
             1)      Adding Single elements

To add a single element, you can call the add() method:

   public boolean add (Object element)  

The add() method takes a single argument of the element to add. If the element is not in the set, it is added and true is returned. If the element happens to be in the set already, because element.equals(oldElement) returns true, then the new element replaces the old element in the collection and false is returned. If the old element has no other references, it becomes eligible for garbage collection.

If the set is read only, then adding an element will throw UnsupportedOperationException.

Note:- If you need to modify an element in a set, you should remove it, modify it and then re-add it. If you don’t, you can consider the object lost as there is no way of finding the object without manually traversing through all the elements. The is true because change affects the results of hashcode().

              2)      Adding Another Collection

You can add a group of elements from another collection to the set with the addAll() method:

    public boolean addAll (Collection c)  

element in the collection passed in will be added to current set via the subsequent call to add() method on each element. If the underlying set changes, true is returned. If no elements are added, false is returned. As with add(), if equal elements are in both sets, true is returned with the new elements replacing the old elements in the set.

If set is read-only , then it will throw UnsupportedOperationException.


Happy LearningJ

No comments:

Post a Comment