Menu
Topics Index
...
`

Creating HashMap and Iterator for it


If you need explanation Read this topic

If you need Answer Take test on this topic

Creating HashMap and Iterator for it
What will be the output of the following program?
import java.util.*;
final class FinalTest {
    final int id;
    String name;
    final HashMap<String, String> testMap = new HashMap<String, String>();
    public int getId() {return id; }
    public String getName() {return name; }
    public HashMap<String, String> getTestMap() {
        return (HashMap<String, String>) Collections.unmodifiableMap(testMap);
    }
    public FinalTest(int i, String name, HashMap<String, String> hm) {
        id = i;
        this.name = name;
        Iterator<String> iterator = hm.keySet().iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
            testMap.put(key, hm.get(key));
        }
    }
}
public class FinalClazz {
    public static void main(String[] args) {
        HashMap<String, String> h1 = new HashMap<String, String>();
        h1.put("1", "first");
        h1.put("2", "second");
        FinalTest ce = new FinalTest(10, "Original", h1);
        System.out.println(ce.getId() + " " + ce.getName() + " " + ce.getTestMap().size());
        h1.put("3", "third");
        ce.name = "Changed";
        System.out.println(ce.getId() + " " + ce.getName() + " " + ce.getTestMap().size());
    }
}

A. 10 Original 2
10 Changed 2
B. 10 Original 2
10 Original 2
C. 10 Original 2
10 Changed 3
D. Compilation Error
E. Runtime Error
Topic: Java Read-only Collections And Algorithms

If you need explanation Read this topic

If you need Answer Take test on this topic

User comments below. All of them might not be correct.

D.compilation error bcz.modifiableMap cannot be casted to HashMap

Posted by Shabaaz Shaikz    2014-03-03 12:57:24


E. Runtime Error. Collections.unmodifiableMap cannot be cast into HashMap

Posted by Nikhil Sulibhavi    2014-03-03 13:31:47


E. Runtime error

Posted by Vinay Jogu    2014-03-03 16:21:17


Congratulations Nikhil Sulibhavi. You are this dose winner. We will send you the link using which you can claim your recharge.
Runtime Error: 'java.util.Collections$UnmodifiableMap cannot be cast to java.util.HashMap'.

Posted by Merit Campus    2014-03-04 04:20:20


© meritcampus 2019

All Rights Reserved.

Open In App