数组:只能存储相同类型的数据,且长度确定后不可改变
集合:只能存引用数据类型(对象),还有可以存自动装箱的基本数据类型
集合的长度可以改变
collection 集合的根接口
1)list 按顺序存储,有下标,可以存重复的数据
ArrayList 数组实现
LinkedList 链表实现
VectorList 数组实现
2)set 不按顺序存储,无下标,不可存重复的数据
hashset 哈希算法
Treeset 二叉树
collection.add() 添加指定元素 返回 boolean
collection.addAll(collection) 添加集合的全部元素
Collection collection = new ArrayList();
collection.isEmpty() 判断集合是否为空 返回boolean
collection.size() 集合长度 返回int
collection.contains() 判断是否包含某个元素 返回boolean
collection.containsAll(collection) 如包含指定集合的所有元素,返回boolean
collection.remove() 删除某个元素
collection.removeAll(collection) 移除本集合与指定集合交集的部分,可以有不想交的元素
coolection.retainall()collection 仅保留两集合交集的部分
collection.clear() 清空集合
遍历字符串集合
Collection collection = new ArrayList();
collection.add("afd");
collection.add("b");
collection.add("c");
collection.add("d");
//将集合转化成数组
Object[] array = collection.toArray();
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
public static void fun4() {
//吹昂见一个集合,添加三个学生,遍利集合打印学生姓名
//多态不能直接调用子类的特有方法
Collection collection = new ArrayList();
collection.add(new Student("赫赫",24));
Object[] array = collection.toArray();//强转数组类型,不能把数组中的元素墙砖
for (int i = 0; i < array.length; i++) {
//数组遍历中要把数组中每一个对象都进行向下转型
Student student = (Student)array[i];
System.out.println(student.getName());
}
}
Iterator iterator = collection.iterator();//获取集合中迭代器
iterator.hasNext() 如果仍有元素可以迭代,则返回 true。
iterator.next() 返回迭代的下一个元素
public static void main(String[] args) {
Collection collection = new ArrayList();
//迭代器遍历时相当于有一个指针指向你的集合
//每next一次,指针就向后移动
collection.add(new Student("mumu",18));
collection.add(new Student("lili",19));
collection.add(new Student("nana",11));
collection.add(new Student("pipi",16));
// //获取集合中的迭代器
// Iterator iterator = collection.iterator();
// boolean b1 = iterator.hasNext();
// System.out.println(b1);
// //判断下一个元素
// 获取下个元素
// Object next = iterator.next();
// System.out.println(next);
//迭代器便利循环数组
//获取集合中的迭代器
Iterator iterator = collection.iterator();
while (iterator.hasNext()) {
//获取集合中的元素
//System.out.println(iterator.next());
Student student = (Student)iterator.next();
System.out.println(student.getName());
}
}