Tuesday, 15 April 2014

Map.Entry : setValue : Replaces the value corresponding to this entry

V setValue(V value)
Replaces the value corresponding to this entry with the specified value. Return old value corresponding to the entry.

import java.util.*;

class MapEntrySetValue{
  public static void main(String args[]){
         Map<Integer, String> myMap = new HashMap<> ();
  
  /* Put the data to Map */
  myMap.put(1, "First");
  myMap.put(2, "Second");
  myMap.put(3, "Third");
  myMap.put(4, "Fourth");
  
  System.out.println("Before Setting");
  System.out.println("Key\tValue");
  for(Map.Entry<Integer, String> entry : myMap.entrySet()){
  System.out.println(entry.getKey()+"\t" + entry.getValue());
  }
  
  System.out.println("\nAfter Setting");
  System.out.println("Key\tValue");
  for(Map.Entry<Integer, String> entry : myMap.entrySet()){
  entry.setValue("default");
  System.out.println(entry.getKey()+"\t" + entry.getValue());
  }
  }
}


Output
Before Setting
Key     Value
1       First
2       Second
3       Third
4       Fourth

After Setting
Key     Value
1       default
2       default
3       default
4       default

1. throws UnsupportedOperationException if the put operation is not supported by the backing map
import java.util.*;

class MapEntrySetValueUnsupported{
  public static void main(String args[]){
         Map<Integer, String> myMap = new HashMap<> ();
  Map<Integer, String> unmodifiable;
  
  /* Put the data to Map */
  myMap.put(1, "First");
  myMap.put(2, "Second");
  myMap.put(3, "Third");
  myMap.put(4, "Fourth");
  
  unmodifiable = Collections.unmodifiableMap(myMap);
  for(Map.Entry<Integer, String> entry : unmodifiable.entrySet()){
  entry.setValue("default");
  System.out.println(entry.getKey()+"\t" + entry.getValue());
  }
  }
}

Output
Exception in thread "main" java.lang.UnsupportedOperationException
      at java.util.Collections$UnmodifiableMap$UnmodifiableEntrySet$Unmodifiab
leEntry.setValue(Collections.java:1488)
      at MapEntrySetValueUnsupported.main(MapEntrySetValueUnsupported.java:17)

2. throws ClassCastException if the class of the specified value
prevents it from being stored in the backing map

3. throws NullPointerException if the backing map does not permit
null values, and the specified value is null

4. throws IllegalArgumentException if some property of this value prevents it from being stored in the backing map





Prevoius                                                 Next                                                 Home

No comments:

Post a Comment