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]
- Java学习11:ArrayList常见题型
- 链表常见题型(java版)
- java校招面试常见题型
- 栈和队列常见题型(java版)
- 常见题型解法
- 面试常见题型总结
- 动态规划常见题型
- 链表常见题型
- javaweb常见面试题型
- CTF常见的题型
- CTF常见题型
- Java学习之ArrayList
- java.util.ArrayList学习
- Java学习之ArrayList
- java源码学习-----ArrayList
- java ArrayList源码学习
- Java ArrayList学习
- JAVA源码学习-ArrayList
- DNX SDK版本 “dnx-clr-win-x86.1.0.0-beta5”无法安装
- 欢迎使用CSDN-markdown编辑器
- Android OpenGL教程-第六课【转】
- clearfix清除浮动的几种方法
- Go错误处理
- Java学习11:ArrayList常见题型
- 好久不用代码实现自定义UItableViewCell
- tst、cmp、bne、beq指令
- 1041. 考试座位号(15)——C语言
- Vue学习小结-1
- CentOS 6.X系统安装
- 微信H5同层播放器以及视频自动播放
- uva 1626
- selenium+eclipse常见问题