Java 基础之 List
Java将容器分为存储键值对的和存储普通对象的,Map是用来存储键值对的,Collection这个接口的子类是用来存储普通对象的。Set元素是不可以重复的,底层实现是hash表,List存放的元素可以重复,逻辑上就是个线性表,LinkedList就是用链表实现的,而ArrayList是用数组实现的。功能上的区别就是这样,到时候根据具体的业务逻辑选择就可以了!
基本方法:
增加元素: add(element), add(index,element)
获得元素: get(index)
修改元素: set(index, element)
删除元素: remove(element), remove(index)
清空列表: clear()
判断包含: contains(element)
判断为空: isEmpty()
列表长度: size()
转为数组: toArray()
//构造一个空的ArrayList,指定存放的是String类型的数据 ArrayList<String> list = new ArrayList<String>(); //Java中的集合不可以添加基本数据类型,必须是引用数据类型;如果要添加基本数据类型,可以使用包装类 list.add("aaa"); // 可以增加重复的元素 list.add("aaa"); list.add("bbb"); //add()是继承Collection的方法;add(index,element)是 List 的方法 list.add(2, "ccc"); //打印整个ArrayList System.out.println(list); //遍历各个元素并打印 for(int i=0; i<list.size();i++){ System.out.print(list.get(i) + " "); } System.out.println("\r\n====================================");
output:
[aaa, aaa, ccc, bbb]
aaa aaa ccc bbb
====================================
//通过index修改该位置的元素 list.set(0, "aa"); System.out.println("After reset, the list is: "+list); System.out.println("====================================");
output:
After reset, the list is: [aa, aaa, ccc, bbb]
====================================
//由 ArrayList 转为 Array,转化后的数据类型是Object Object[] array = list.toArray(); for(Object elem : array){ System.out.print(elem + " "); } System.out.println("\r\nThe lenght of the array is: " + array.length); System.out.println("====================================");
output:
aa aaa ccc bbb
The lenght of the array is: 4
====================================
//删除元素,可以传入下标,也可以传入元素 String removed = list.remove(0); System.out.println("The removed element is: "+removed); System.out.println(list); boolean removed2 = list.remove("aaa"); System.out.println(removed2); System.out.println(list); System.out.println("====================================");
output:
The removed element is: aa
[aaa, ccc, bbb]
true
[ccc, bbb]
====================================
//判断集合是否包含某个元素 System.out.println("list contains aaa? : "+list.contains("aaa")); //判断集合是否为空 System.out.println("list is empty? : "+list.isEmpty()); //获得第一个元素 System.out.println("The fisrt element is: " + list.get(0)); System.out.println("====================================");
output:
list contains aaa? : false
list is empty? : false
The fisrt element is: ccc
====================================
//清空整个集合 list.clear(); System.out.println("Afer clear, the list is: "+list); System.out.println("====================================");
output:
Afer clear, the list is: []
====================================
//遍历集合各个元素:方法1 for(int i=0; i<list.size();i++){ System.out.print(list.get(i) + " "); } //遍历集合各个元素:方法2 for(String el: list){ System.out.print(el + " "); } //遍历集合各个元素:方法3 Iterator<String> iterator = list.iterator(); while(iterator.hasNext()){ String el = iterator.next(); System.out.println(el); }