各位看官们,大家好,上一回中咱们说的是Java中类集的例子,这一回咱们说的例子是Java中的类集之List。闲话休提,言归正转。让我们一起Talk Android吧!
看官们,我们在上一章回中对Java中的类集做了概述性的介绍,这一回中我们将对类集中具体的接口和类进行介绍,这一回主要介绍List接口和它的实现类ArrayList
。这个List
就是我们在数据结构中的列表,或者叫线性表。List
是Connection
接口的子接口,ArrayList
是它的实现类,接下来我们看看如何使用它们。
看官们,对列表的操作可以简单概括为:获取,添加,修改和删除,这些操作都有相对应的方法。
- 从列表中获取元素的方法:
obj get(index);
- 向列表中添加元素的方法:
add(obj),add(index,obj);
- 修改列表中元素的方法:
set(index,obj);
- 删除列表中元素的方法:
remove(index);remove(obj)
。
这些方法有一个obj
参数,它表示列表中的元素。接下来我们通过具体的代码来介绍如何使用这些方法来操作列表。
public class ListEx {
public static void main(String args[]){
//init ArrayLisst
List<Integer> list = new ArrayList<>();
for(int i=0; i<10;++i){
//list.add(new Integer(i+1));
list.add((i+1));
}
//show size of list ,and content of list
System.out.println("size of list: "+list.size());
for(Integer i:list)
System.out.print(i+" ");
System.out.println();
System.out.println("list: "+list);
//change list to array
Integer [] array = list.toArray(new Integer [] {});
System.out.println("change list to array: "+Arrays.toString(array));
//add a content at location 8 of list
list.add(7,6);
System.out.println("add 6 at location 8 of list: "+list);
//get the content of list
System.out.println("the first content is: "+list.get(0));
//change the content of list
System.out.println("change the first content from "+list.get(0)+" to 9.");
list.set(0,9);
System.out.println("list: "+list);
//get the location of content
System.out.println("the content 3 is located: "+list.indexOf(3));
//delete the content of list,this is based on content of list
list.remove(new Integer(9));
System.out.println("after removing the content 9: "+list);
//delete the content of list,this is based on location of list
list.remove(9);
System.out.println("after removing the 9th content: "+list);
}
}
关于这些方法我说一下注意事项:
add
和remove
方法都是重载方法,可以依据具体情况来选择。- 添加元素时如果不指定添加的位置,那么默认在列表末尾添加元素。
- 删除元素时如何想删除指定位置的元素,那么需要确定该位置是有效的位置,不然会有异常。
比如列表长度为5,也就是说有5个位置存放元素,那么大于4或者小于0的位置都是无效位置。列表中元素的位置和数组中元素的下标是相同的,因此在进行列表中有关位置的操作时,可以把位置看作是数组中的下标。
下面是程序的运行结果,请参考:
size of list: 10
1 2 3 4 5 6 7 8 9 10
list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
change list to array: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
add 6 at location 8 of list: [1, 2, 3, 4, 5, 6, 7, 6, 8, 9, 10]
the first content is: 1
change the first content from 1 to 9.
list: [9, 2, 3, 4, 5, 6, 7, 6, 8, 9, 10]
the content 3 is located: 2
after removing the content 9: [2, 3, 4, 5, 6, 7, 6, 8, 9, 10]
after removing the 9th content: [2, 3, 4, 5, 6, 7, 6, 8, 9]
看官们,ArrayList
底层使用数组来实现,不过与数组相比,它的大小可以动态调节,这也是它最受欢迎的地方,我们只需要往里面添加元素就行,不用管它是否可以容纳的下这些数据,真是个“大胃王”呀。此外,它也可以转换为数组。
List
接口的实现类中还有一个Vector
类,它类似ArrayList
类,不过它主要用在线程安全的操作中。还有就是一些老的代
码中,因为它比ArrayList
诞生的早。在实际项目中,除非有线程安全的需要,否则使用ArrayList
就可以。
各位看官,关于Java中类集之List的例子咱们就介绍到这里,欲知后面还有什么例子,且听下回分解!