What will the given hashMap contain, after the below code is compiled and run?

    public static void main(String[] args) {
        HashMap hashMap = new HashMap();
        List list = new ArrayList();
        list.add(hashMap);
        hashMap.put(list, null);
        hashMap.put(list, null);
    }
Explanation
When a key-value pair is added to a HashMap - a hashCode for the input key is generated, while the value can be virtually anything, even null. An ArrayList hashCode is calculated based on the hashCodes of all of its elements. Consequently, adding the list first time, will generate no error, because the hashMap is empty, and the list hashCode can be easily calculated. The second addition, however, will generate a StackOverflowError (the list hashCode needs to be calculated based on HashMap hashCode, which needs to be calculated based on the list hashCode, etc).

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback
Keep exploring
Java quizzes
Cosmo
Sign Up Now
or Subscribe for future quizzes