java中的容器类

来源:互联网 发布:linux 文件夹 不同组 编辑:程序博客网 时间:2024/05/29 18:16

容器类的总的结构图如图:


Collection类分为 Set, 和 List


Set:  实现了Set接口的类, 里面的元素无序, 但不可以重复

List: 实现了List接口的类, 里面的元素有序, 但可以重复

代码:

<span style="font-size:24px;">import java.util.*;public class TestPoint{static int a[] = {1,  3, 2, 4, 5, 0, 9, 1, 4};public static void main(String args[]){testList();testSet();}public static void testList(){ArrayList<Integer> arrayList = new ArrayList<Integer>();for(int i : a){arrayList.add(i);}for(Integer In : arrayList){System.out.print(In + " ");}System.out.println();}public static void testSet(){HashSet<Integer>hashSet = new HashSet<Integer>();for(int i : a){hashSet.add(i);}for(Integer In : hashSet){System.out.print(In + " ");}System.out.println();}}</span>

结果为:

1 3 2 4 5 0 9 1 4 
0 1 2 3 4 5 9   //自带排序功能


迭代器遍历容器

代码:

<span style="font-size:24px;">public class TestPoint{static int a[] = {1,  3, 2, 4, 5, 0, 9, 1, 4};public static void main(String args[]){testList();}public static void testList(){ArrayList<Integer> arrayList = new ArrayList<Integer>();for(int i : a){arrayList.add(i);}/*for(Integer In : arrayList) //foreach的用法{System.out.print(In + " ");}*/Iterator <Integer> it = arrayList.iterator(); //迭代器遍历while(it.hasNext()){System.out.print(it.next() + " ");}}}</span>


补充一点, map集合,以后介绍,map实在太好用了






0 0
原创粉丝点击