二十一、JAVA中的集合Collection

1. Collection接口的概述

是用来存放对象的数据结构。其中长度可变,而且集合中可以存放不同类型的对象。并提供了一组操作成批对象的方法。

数组的缺点:长度是固定不可变的,访问方式单一,插入、删除等操作繁琐。

2. 集合的继承结构

在这里插入图片描述

Collection接口
-- List接口  : 数据有序,可以重复。
   -- ArrayList子类
   -- LinkedList子类
-- Set接口  : 数据无序,不可以存重复值
   -- HashSet子类
-- Map接口  : 键值对存数据
-- HashMap
Collections工具类

3. 常用方法

boolean add(E e):添加元素。
boolean addAll(Collection  c):把小集合添加到大集合中 。
boolean contains(Object o) : 如果此 collection 包含指定的元素,则返回 trueboolean isEmpty() :如果此 collection 没有元素,则返回 trueIterator<E> iterator():返回在此 collection 的元素上进行迭代的迭代器。
boolean remove(Object o) :从此 collection 中移除指定元素的单个实例。
int size() :返回此 collection 中的元素数。
Objec[] toArray():返回对象数组

4. 案例测试常用方法

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class TestCollection {
       public static void main(String[] args) {
              Collection c = new ArrayList();//接口无法直接创建对象
              c.add("hello");//添加元素
              c.add("java");//添加元素
              c.add("~");//添加元素
              c.add(10);//jdk5后有自动装箱功能,相当于把10包装Integer.valueOf(10)
              System.out.println(c.remove("~"));//移除元素
              System.out.println(c.contains("a"));//判断包含关系
              System.out.println(c.size());//集合的长度
              System.out.println(c);
             
              //for遍历集合
              for(int i =0 ;i<c.size();i++) {
                     System.out.println(c.toArray()[i]);
              }
              //iterator迭代器遍历
              Iterator it = c.iterator();//对 collection 进行迭代的迭代器
              while (it.hasNext()) {//如果仍有元素,则返回 true
                     System.out.println(it.next());//返回迭代获取到的下一个元素
              }
                 
        } 
 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值