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();
        hashMap.put(list, null);
        hashMap.put(list, null);
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).

Следи за CodeGalaxy

Мобильное приложение Beta

Get it on Google Play
Обратная Связь
Продолжайте изучать
тесты по Java
Зарегистрируйся сейчас
или Подпишись на будущие тесты