Machine-translated by Google. Questions are authored in English.
Top

Discussion

What will be the output of the program?

import java.util.*;

public class Fragment98
{
    public static void main(String[] args)
    {
        Map<String, String> m = new LinkedHashMap<String, String>();
        m.put("a", "1");
        m.put("b", "2");
        Iterator<String> it = m.keySet().iterator();
        it.next();
        it.remove();
        System.out.println(m);
    }
}

  • A.The program prints {a=1, b=2}
  • B.The program prints {b=2}
  • C.The program prints {a=1}
  • D.A ConcurrentModificationException is thrown.

Answer: B

Removing through the key-set iterator is the supported way to delete during iteration, and because the set is a view the whole entry goes from the map. Insertion order leaves a first, so a is the one removed and {b=2} remains.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.