集合

集合概念

Collection接口
List接口
List接口的实现类
1.ArrayList
2.Vector
3.LinkedList

集合概念
对象的容器,实现了对对象常用的操作,类似数组
Collection:集合体系的根接口
List接口:有序,有下标,元素可重复
Set接口:无序,无下标,元素不可重复

Collection接口
添加元素

//创建一个ArrayList集合
Collection collection = new ArrayList();
collection.add("苹果");
collection.add("西瓜");
collection.add("梨");
//输出集合中元素的个数
System.out.println(collection.size());
//输出集合的内容
System.out.println(collection);

删除元素

//删除某个元素
collection.remove("西瓜");
System.out.println(collection.size());
System.out.println(collection);
//清空集合中的所有元素
collection.clear();

遍历元素
使用增强for循环来遍历,或者迭代器
迭代器iterator三个方法
1.hasNext:判断是否有下一个,返回布尔值
2.next:有元素的话输出
3.remove:移除这个元素,不能使用collection的方法

//遍历
System.out.println("++++++++++++++++++++++++");
for (Object a : collection) {
    System.out.println(a);
}
System.out.println("++++++++++++++++++++++++");
//迭代器遍历集合元素并删除
Iterator iterator = collection.iterator();
while (iterator.hasNext()) {
    System.out.println(iterator.next());
    iterator.remove();

}
System.out.println(collection.size());

判断是否存在

//判断
    //如果有返回true,没有返回false
    System.out.println(collection.contains("橘子"));
    System.out.println(collection.isEmpty());
}

集合操作对象
此处我们创建了Student的pojo类,用来操作
每次new Student的时候执行有参构造方法传到对象中

Collection list = new ArrayList();
Student s1 = new Student("张三", 22);
Student s2 = new Student("李四", 20);
Student s3 = new Student("魏忠贤", 99);
//添加
list.add(s1);
list.add(s2);
list.add(s3);
System.out.println(list);
//删除
//list.remove(s1);
System.out.println(list);
//遍历
for (Object student: list) {
    System.out.println(student);
}
//迭代器遍历
Iterator iterator = list.iterator();
while(iterator.hasNext()){
    System.out.println(iterator.next());
}

List接口
indexOf 方法可以获取某个元素在集合中对应的位置(下标)
列表迭代器ListIterator
ListIterator 可以实现从后往前遍历
nextIndex 方法可以输出集合下标
hasPrevious previousIndex previous

List list = new ArrayList();
list.add("苹果");
list.add("梨");
list.add("香蕉");
ListIterator iterator = list.listIterator();
while(iterator.hasNext()){
    //nextIndex方法可以输出集合中元素的下标
    System.out.println(iterator.nextIndex()+":"+iterator.next());
}
//从后往前遍历
while (iterator.hasPrevious()){
    System.out.println(iterator.previousIndex()+":"+iterator.previous());
}

List补充方法
subList

//输出对应两个下标之间的元素,前包后不包
System.out.println(list.subList(1, 2));
System.out.println(list);

List接口的实现类
1.ArrayList
数组结构实现:查询快,增删慢,线程不安全

2.Vector
数组结构实现:查询快,增删慢,线程安全
3.LinkedList
链表结构实现:查询慢,增删快`

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值