Java学习11:ArrayList常见题型

来源:互联网 发布:沙巴克传奇有哪些端口 编辑:程序博客网 时间:2024/06/03 08:32

Identify the errors in the following code.

    ArrayList<String> list = new ArrayList<>();    list.add("Denver");    list.add("Austin");    list.add(new java.util.Date());    String city = list.get(0);    list.set(3, "Dallas");    System.out.println(list.get(3));

Answer:
Error 1:list.add(new java.util.Date()); is wrong, because it is an array list of strings. You cannot add Date objects to this list.
Error 2:list.set(3, “Dallas”);is wrong because there is no element at index 3 in the list.
Error 3:list.get(3)is wrong because there is no element at index 3 in the list.

remove(“Dallas”)

Suppose the ArrayList list contains {“Dallas”, “Dallas”, “Houston”, “Dallas”}. What is the list after invoking list.remove(“Dallas”) one time? Does the following code correctly remove all elements with value “Dallas” from the list? If not, correct the code.
for (int i = 0; i < list.size(); i++)
list.remove(“Dallas”);
Answer:
After list.remove(“Dallas”), the list becomes {“Dallas”, “Houston”, “Dallas”}. No. Here is the reason: Suppose the list contains two string elements “red” and “red”. You want to remove “red” from the list. After the first “red” is removed, i becomes 1 and the list becomes {“red”}. i < list.size() is false. So the loop ends. The correct code should be

for (int i = 0; i < list.size(); i++) {  if (list.remove(element))    i--;}//orwhile(string.contains("Dallas"))    string.remove("Dallas");

why code displays [1, 3] rather than [2, 3]

Explain why the following code displays [1, 3] rather than [2, 3].

    ArrayList<Integer> list = new ArrayList<>();    list.add(1);    list.add(2);    list.add(3);    list.remove(1);    System.out.println(list);

How do you remove integer value 3 from the list?
Answer:
The ArrayList class has two overloaded remove method remove(Object) and remove(int index). The latter is invoked for list.remove(1) to remove the element in the list at index 1.

        ArrayList<Integer> list = new ArrayList<>();        list.add(1);        list.add(2);        list.add(3);        list.remove((Integer) 3);        System.out.println(list);//[1,2]
原创粉丝点击