容器的基本使用

 

本文将介绍容器的基本使用方法,包括增加、删除、遍历、查询。

 

Collection容器

 

Collection容器可以通过Collection和Iterator接口来统一操作。容器只能存储对象,不能存储基本数据类型,可以使用基本数据类型的包装类来存储基本类型。容器有两种构造方法:构造空容器和非空容器。看下面的示例代码:

 

//构造空容器
Collection<Integer> collection = new ArrayList<Integer>();
collection.add(10);//向容器添加元素
collection.add(20);
collection.add(30);
//构造非空容器
Collection<Integer> collection1 = new ArrayList<Integer>(collection);

 

构造空容器时构造函数没有任何参数。构造非空容器时构造函数有一个Collection参数,可以从任何已有的Collection容器构造新容器,新容器将包含已有容器的所有元素。

 

Collection接口继承自Iterable接口,每个Collection容器都可以调用iterator方法获取到一个迭代器,通过迭代器可以遍历容器中的每一个元素。 因为实现了Iterable接口,所以可以使用foreach语法来遍历容器,foreach使用迭代器在容器中移动数据。容器遍历示例如下:

 

Collection<Integer> collection = new ArrayList<Integer>();
collection.add(10);
collection.add(20);
collection.add(30);
//迭代器遍历
Iterator iter = collection.iterator();
while(iter.hasNext()){
    System.out.println(iter.next());
}
//foreach 遍历
for(Integer c: collection){
    System.out.println(c);
}

 

容器的增加、删除操作示例如下:

 

Collection<Integer> collection = new ArrayList<Integer>();
Integer i = 40;
collection.add(i); //增加
collection.remove(i); //删除

 

Map容器

 

Map是用来存储一组键值对(key,value)的容器,同Collection一样Map容器也有空容器和非空容器构造方法,示例如下:

 

Map <Integer, Integer> m = new HashMap();
m.put(1, 1);//插入键值对
Map <Integer, Integer> m2 = new HashMap(m);

 

Map没有实现Iterable接口,所以不能使用迭代器和foreach遍历Map。Map的entrySet方法可以获取到键值对的集合,它是一个Set里面存储了Entry对象,Entry对象包含键和值,我们通过遍历这个Set来达到遍历Map的效果。示例如下:

 

Map <Integer, Integer> m = new HashMap();
m.put(1, 1);
for(Map.Entry<Integer,Integer> e: m.entrySet()){
    System.out.println("key:" + e.getKey());
    System.out.println("value:" + e.getValue());
}

 

Map的增删示例如下:

 

Map <Integer, Integer > m = new HashMap();
Integer i = 1;
m.put(i, 1); //增加
m.remove(i); //删除

 

最后

 

本文只是介绍了通过Collection和Map接口来访问容器,每个具体的容器都提供了一些特殊的方法来操作数据,后面讲到具体的类型时再介绍使用方法。

【水煮Java】
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值