Collection接口其中包含一些主要的常见方法,如:
size();
isEmpty();
clear();
contains();
add();
remove();
同时,Collection集合类中还存在List与Set以及Map集合类,统称为Collection三大集合类。这三种对象与本身的Collection类似,也可以存储字符串并进行例如遍历等操作。但是每种集合类又具有一些其他集合类所不具有的特殊功能。本文主要列出List的相关应用方法与应用细节。
首先,这里先区别List类与Set类最大的区别是List类元素有序,存储顺序和取出顺序一致,元素可以重复;但是Set类内部的元素是无序的,且元素是唯一的。
List在构造新变量时与Collection一样,通过
List list = new ArrayList();
来进行创建。
添加元素时,可以使用
void add(int index,Object obj);
index可以是缺省值,默认在顺序添加元素,Index不缺省时则表示在指定的索引位置添加元素。
List也可以将自己创建的class对象添加进去:
list.add(Student s1);
同时,迭代器iterator()也可以正常使用(如has.next()与next()函数)。
在List中删除指定索引位置的元素,同时还能够把删除掉的元素值返回,使用如下函数:
Object remove(int index);
List还支持给定索引位置查找值并将其返回:
Object get(int index);
还可以指定修改索引出的元素为给定的元素,并返回被修改的值,调用如下方法:
Object set(int index, E element);
根据以上的种种方法我们可以总结出,List集合类有一种特有的遍历方法——使用普通for循环,通过size()方法和get()方法结合使用:
For(int x = 0; x < list.size();x++){
String s = (String) list.get(x);
System.out.println(s);
}
最后来说一说ListInterator列表迭代器,它继承自迭代器。因此,它具有hasNext()和next()方法;同时,在创建它时,使用了多态原理:
ListInterator lit = list.listInterator();//多态
While(lit.hasNext()){
String s = (String) lit.next();
System.out.println(s);
}
ListInterator还具有逆向遍历的特殊功能,不过在实际使用过程中意义不是很大,原因是这种方法需要先进行正向遍历,才能够进行逆向遍历操作:
ListIterator lit = list.listIterator();
while (lit.hasNext()) {
String s = (String) lit.next();
System.out.println(s);
}
System.out.println("---------------");
// 逆向遍历
System.out.println(lit.hasPrevious());
while (lit.hasPrevious()) {
String s = (String) lit.previous();
System.out.println(s);
}
如上,如果上方的正向遍历循环未进行,则hasPrevious()函数会给出false返回值。