什么是集合
概念:对象的容器,定义了对多个对象进行操作的常用方法。可实现数组的功能。
和数组的区别:
数组长度固定,集合长度不固定
数数组可以存储基本类型和引用类型,集合只能存储引用类型
位置:java.util.*;
Collection体系集合
Collection接口
特点:代表一组任意类型的对象,无序、无下标、不能重复。
方法:
boolean add(Object obj) //添加一个对象。
boolean addAll(Collection c) //将一个集合中的所有对象添加到此集合中。
void clear() //清空此集合中的所有对象。
boolean contains(Object o) //检查此集合中是否包含o对象
boolean equals (Object o) //比较此集合是否与指定对象相等。
boolean isEmpty() //判断此集合是否为空
boolean remove(Object o) //在此集合中移除o对象
int size() //返回此集合中的元素个数。
Object[] toArray() //将此集合转换成数组。
public class Demo1 {
public static void main(string[] args){
Collection collection = new ArrayList();
//1.添加元素
cllection.add("苹果");
cllection.add("榴莲");
System.out.println(collection);
//2.删除元素
collection.remove("苹果");
//3.遍历元素
//3.1使用增强for
for (Object object : collection) {
System.out.println(object);
}
//3.2使用迭代器
//hasNext()有没有下一个元素
//next();获取下一个元素
//remove();删除当前元素
Iterator it = collection.iterator();
while(it.hasNext()) {
String s = (String)it.next();
System.out.println(s);
//迭代中不能使用collection删除方法
//collection.remove(s);
it.remove();
}
//4.判断
System.out.println(collection.contains("西瓜"));
System.out.println(collection.isEmpty());
}
}
List接口
特点:有序、有下标、元素可以重复。
方法
void add(int index,Object o) //在index位置插入对象o。
boolean addAll(int index,Collection c) //将一个集合中的元素添加到此集合中的index位置。
Object get(int index) //返回集合中指定位置的元素。
List subList(int fromIndex,int toIndex) //返回fromIndex和toIndex之间的集合元素。
public class Demo2 {
public static void main(string[] args){
List list = new ArrayList<>();
//1.添加元素
list.add("苹果");
//2.删除元素
list.remove("苹果");
//3遍历
//3.1使用for遍历
for(int i=0;i<list.size();i++){
System.out.println(list.get(i));
}
//3.2使用增强for
for(Object object : list){
System.out.pri