255.
String fruit1 = fruits.getOrDefault(1,”Mango”);
//returns apple
String fruit2 = fruits.getOrDefault(3,”Mango”);
//returns mango
This code creates a map called fruits with an Integer key and
a String value. It adds some values to the map. It first uses the
getOrDefault method to retrieve the value corresponding to
the key 1 passing
the default value as Mango. Since there is a
value in the Map with key
1, fruit1 is assigned the value
corresponding
to the key which is Apple. It then uses the
getOrDefault method to retrieve the value corresponding to
the key
3 passing the default value as
Mango. Since there is no
value
in the map with key 3, fruit2 is assigned the default
value
Mango.
What is the output of the following code snippet?
Map
fruits = new HashMapString>();
fruits.put(1,”Apple”);
fruits.put(2,”Orange”);
fruits.put(3,”Strawberry”);
fruits.replace(1, “Mango”); //Line 1
fruits.replace(2, “Orange”,”Banana”); //Line 2
fruits.replace(3, “Blackberry”,”Pineapple”); //Line 3
System.out.println(fruits.get(1));
System.out.println(fruits.get(2));
System.out.println(fruits.get(3));
Answer:
This code prints the following output:
256.
•
•
•
Mango
Banana
Strawberry
The Map.replace(key, value) method replaces a value
only if it is mapped to a value. In the above example, the key
1 is
mapped to the value
Apple, so the replace() method replaces
the value
Apple with the value
Mango. The
Map.replace(key, oldValue, newValue) replaces a
value only if it is mapped to the specified value. In the above
example, the key
2 is mapped to the value
Orange. So, the
replace method at Line 2
replaces the value Orange with the
value
Banana. Also, the key
3 is mapped to the value
Do'stlaringiz bilan baham: