我以前端的角度去看Java中的List,觉得List就像js中的数组。
List操作的常用方法:
一:添加–add()
List<String> list = new ArrayList<String>();
list.add("hello");
list.add("world");
list.add("hello"); //可以添加重复的值
二:删除–remove(index) 按索引值删除 remove(Object o) 按元素内容删除
list.remove(0);
list.remove("hello"); //注意! 只会删除匹配到的第一个"hello"
三:获得–get(index) 包含–contains(Object o)
list.get(0);
list.contains("hello") // 返回true
list.contains("china") //返回false
四:替换–set(index,ele) add(index,ele)
list.set(0,"hey") //把原来索引为0的元素“hello”替换为 “hey”
list.add(0,"hi") //把原来索引为0的元素向后移一位,并不会被替换
五:截取–subList(startindex,endindex)
list = list.subList(0,3); //截取后的List不包含索引为3的元素 总结起来就是 含头不含尾
六:遍历 这里介绍三种方法
for(Iterator it = list.iterator; it.hasNext();){
String ele = it.next();
system.out.println(ele);
}
for(int i = 0; i<list.size(); i++){
system.out.println(list.get(i));
}
for(String data : list){
system.out.println(data);
}