java集合类的基本方法的使用

欢迎进入Java社区论坛,与200万技术人员互动交流 >>进入

if(collection.isEmpty())

System.out.println(“collection is Empty!”);

//使用collection.isEmpty()方法来判断

}

}|||

程序的运行结果为:

iterator = s1

iterator = s2

iterator = s3

collection is not Empty! size=3

remove: s1

remove: s2

remove: s3

还有元素

collection is Empty!

可以看到,Java的Collection的Iterator 能够用来,:

1) 使用方法 iterator() 要求容器返回一个Iterator .第一次调用Iterator 的next() 方法时,它返回集合序列的第一个元素.

2) 使用next() 获得集合序列的中的下一个元素.

3) 使用hasNext()检查序列中是否元素.

4) 使用remove()将迭代器新返回的元素删除.

需要注意的是:方法删除由next方法返回的最后一个元素,在每次调用next时,remove方法只能被调用一次 .

大家看,Java 实现的这个迭代器的使用就是如此的简单.Iterator(跌代器)虽然功能简单,但仍然可以帮助我们解决许多问题,同时针对List 还有一个更复杂更高级的ListIterator.您可以在下面的List讲解中得到进一步的介绍.

我们看一个List的例子:

import java.util.*;

public class ListIteratorTest {

public static void main(String args) {

List list = new ArrayList();

list.add(“aaa”);

list.add(“bbb”);

list.add(“ccc”);

list.add(“ddd”);

System.out.println(“下标0开始:”+list.listIterator(0).next());//next()

System.out.println(“下标1开始:”+list.listIterator(1).next());

System.out.println(“子List 1-3:”+list.subList(1,3));//子列表

ListIterator it = list.listIterator();//默认从下标0开始

//隐式光标属性add操作 ,插入到当前的下标的前面

it.add(“sss”);

while(it.hasNext()){

System.out.println(“next Index=”+it.nextIndex()+“,Object=”+it.next());

}

//set属性

ListIterator it1 = list.listIterator();

it1.next();

it1.set(“ooo”);

ListIterator it2 = list.listIterator(list.size());//下标

while(it2.hasPrevious()){

System.out.println(“previous Index=”+it2.previousIndex()+“,Object=”+it2.previous());

}

}

}

程序的执行结果为:

下标0开始:aaa

下标1开始:bbb

子List 1-3:[bbb, ccc]

next Index=1,Object=aaa

next Index=2,Object=bbb

next Index=3,Object=ccc

next Index=4,Object=ddd

previous Index=4,Object=ddd

previous Index=3,Object=ccc

previous Index=2,Object=bbb

previous Index=1,Object=a

[1][2]

发光并非太阳的专利,我也可以发光 。

java集合类的基本方法的使用

相关文章:

你感兴趣的文章:

标签云: