Friday 18 April 2014

HashSet : addAll : Add Collection of Data to HashSet

public boolean addAll(Collection<? extends E> c)
Adds all of the elements in the specified collection to this set if they're not already present. Returns true if this set changed as a result of the call.

import java.util.*;
class HashSetAddAll{
 public static void main(String args[]){
  Set<Number> mySet = new HashSet<> ();
  List<Integer> myList = new ArrayList<> (); 
  
  /* Add Data to mySet */
  for(int i=0; i<10; i++)
   mySet.add(i);
   
  /* Add Data to myList */
  for(int i=5; i < 15; i++)
   myList.add(i);
   
  System.out.println("Data in mySet is\n" + mySet);
  System.out.println("\nData in myList is\n" + myList);
  
  /* Add Collection myList to mySet */
  mySet.addAll(myList);
  
  System.out.println("\nAfter adding myList to mySet Data in mySet is ");
  System.out.println(mySet);
 }
}

Output
Data in mySet is
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Data in myList is
[5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

After adding myList to mySet Data in mySet is
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

1. addAll() throws UnsupportedOperationException if the addAll operation is not supported by this set.
import java.util.*;
import java.util.*;
class HashSetAddAllUnsuport{
 public static void main(String args[]){
  Set<Integer> mySet = new HashSet<> ();
  List<Integer> myList = new ArrayList<> ();
  Set<Integer> unModifiableSet; 
  
  /* Add Data to mySet */
  for(int i=0; i<10; i++)
   mySet.add(i);
   
  /* Add Data to myList */
  for(int i=5; i < 15; i++)
   myList.add(i);
   
  System.out.println("Data in mySet is\n" + mySet);
  System.out.println("\nData in myList is\n" + myList);
  
  unModifiableSet = Collections.unmodifiableSet(mySet);
  
  System.out.println("\nData in unModifiableSet is");
  System.out.println(unModifiableSet);
  
  /* Tring to add myList to unModifiableSet */
  unModifiableSet.addAll(myList);
 }
}

Output
Data in mySet is
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Data in myList is
[5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

Data in unModifiableSet is
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Exception in thread "main" java.lang.UnsupportedOperationException
        at java.util.Collections$UnmodifiableCollection.addAll(Collections.java:
1085)
        at HashSetAddAllUnsuport.main(HashSetAddAllUnsuport.java:26)

You can't add data to unmodifiable Set. So Above program throws UnsupportedOperationException.


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment