JAVA SE(十三)—— JAVA 集合框架1(集合框架基本介绍)

一、集合框架基本概念

集合是长度可变的用于存取数据的容器,可以存储不同类型的对象,存储的都是对象的引用(地址)。

二、集合框架基本分类

1、集合框架图解
图片源自网络
2、基本分类
Collection接口
Map接口

三、JAVA包装类

1、基本数据类型对应的包装类

int:Integer
byte: Byte
short:Short
long:Long
float:Float
double:Double
char:Character
boolean:Boolean

四、Collection接口

1、Collection接口基本概念
Collection接口定义了存取一组对象的方法,其子接口Set和List分别定义了存储方式。

2、Collection主要方法摘要

  • boolean add(); 添加元素到 collection
  • void clear(); 移除此 collection 中的所有元素
  • boolean contains(); 如果此 collection 包含指定的元素,则返回 true
  • boolean equals(); 比较此 collection 与指定对象是否相等
  • int hashCode(); 返回此 collection 的哈希码值
  • boolean isEmpty(); 判断此 collection 是否为空
  • Iterator<object> iterator(); 返回在此 collection 的元素上进行迭代的迭代器
  • boolean remove(); 从此 collection 中移除指定元素的单个实例,如果存在的话
  • int size(); 返回此 collection 中的元素数
  • Object[] toArray(); 返回包含此 collection 中所有元素的数组

举例说明某些方法

public class CollectionDemo{
	public static void main(String[] args) {
		Collection c = new ArrayList();
		c.add("hello");
		c.add(1);
		c.add('a');
		c.add(new Integer(100));
		System.out.println("是否成功移除'a':" + c.remove('a'));
		System.out.println("集合是否为空:" + c.isEmpty());
		System.out.println("集合是否包含'helllo':" + c.contains("hello"));
		System.out.println("集合数据有:" + c);
		System.out.println("集合长度 = " + c.size());
		//将集合转成String类型的数组并输出
		Object[] array = c.toArray();
		System.out.print("数组里面的元素有:");
		for(Object i: array) {
			System.out.print(i + " ");
		}
		c.clear();		//清空集合
		System.out.println("\n集合中是否还有元素:" + c);
	}
}
得到如下结果:
是否成功移除'a'true
集合是否为空:false
集合是否包含'helllo'true
集合数据有:[hello, 1, 100]
集合长度 = 3
数组里面的元素有:hello 1 100 
集合中是否还有元素:[]

五、Iterator接口

1、基本概念
在上面示例中,利用System.out.println("集合数据有:" + c);直接打印集合c相当于调用了toString()方法。除了这种方式外,Collection有其特有的输出方式:迭代器Iterator。

//获取迭代器
Iterator it = c.iterator();
System.out.println("利用迭代器iterator输出结果为:");
while(it.hasNext()) {
	System.out.print(it.next() + " ");
}
//输出结果为
利用迭代器iterator输出结果为:hello 1 100 

另外,也可以用for循环输出
System.out.print("利用迭代器iterator输出结果为:");
for(Iterator it = c.iterator(); it.hasNext(); ) {
	System.out.print(it.next() + " ");
}
//输出结果同样为
利用迭代器iterator输出结果为:hello 1 100 

所有实现了Collection接口的集合类都有一个Iterator方法,用于返回一个实现了Iterator接口的对象,Iterator对象称作迭代器,用以方便的实现对集合内元素的遍历操作。

2、Iterator主要方法摘要

  • boolean hasNext(); //判断游标右边是否还有元素
  • Object next(); //返回游标右边的元素并将游标移动到下一个位置
  • void remove(); //删除游标左面的元素,在执行完next()方法之后该操作只能执行一次
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

TwoYellowGuns

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值