• 2022-06-14
    判断下列程序是否能正常运行,如果能,写出运行结果,如果不能,写出错误原因并进行纠正。import java.util.*;import java.util.Map.*;public class Demo {public static void main(String[] args) {Map map = new HashMap();map.put(1, "Tom");map.put(2, "Lucy");map.put(3,"Annie");Set keySet = map.keySet();Iterator it = keySet.iterator();while (it.hasNext()) {Object key = it.next();System.out.println(key);map.remove(key);}}}
  • 不能正常运行,当进行map.remove()操作时会抛出ConcurrentModificationException异常,map中的元素需要通过迭代器进行移除。示例代码如下所示:Set<;Entry<;String, Integer>;>; set=map.entrySet();Iterator<;Entry<;String, Integer>;>; iterator=set.iterator();while(iterator.hasNext()){Entry<;String, Integer>; entry=iterator.next();String name=entry.getKey();if(name.contains("李")){//特别注意:不能使用map.remove(name) 否则会报同样的错误iterator.remove();}}

    举一反三

    内容

    • 0

      给定如下Java代码,编译运行的结果是( )。public class Test { public static void main(String&#91;&#93; args) { Map&#91;String, String&#93; map = new HashMap&#91;String, String&#93;(); String s = "code"; map.put(s, "1"); map.put(s, "2"); System.out.println(map.size()); }} A: 编译时发生错误 B: 运行时引发异常 C: 正确运行,输出:1 D: 正确运行,输出:2

    • 1

      下列关于Map集合的使用说法错误的一项是()。 A: Map用put(key,value)方法来添加一个值。 B: Map用get(key)方法获取与key键相关联的值。 C: Map接口的keySet()方法返回一个有序集合。 D: Map接口中的entrySet()方法返回了一个集合对象。

    • 2

      给定如下Java代码,编译运行的结果是( )。public class Test {public static void main(String&#91;&#93; args) {Map&lt;String, String&gt; map = new HashMap&lt;String, String&gt;();String s = &quot;code&quot;;map.put(s, &quot;1&quot;);map.put(s, &quot;2&quot;);System.out.println(map.size());}} A: 正确运行,输出:1 B: 编译时发生错误 C: 运行时引发异常 D: 正确运行,输出:2

    • 3

      19、下列Java程序代码,运行后的结果是( )。[br][/br]...... HashMap map = new HashMap(); map.put("name", Tom); map.put("name", Marry); A: 0 B: C: 1 D: 2

    • 4

      HashMap&lt;Integer,String&gt; map = new HashMap( );map.put(1,"one");map.put(2,"two");map.put(3,"three");map.put(1,"four");