集合框架
对象数组的概念和使用
对象数组就是数组里的每个元素都是类的对象,赋值时先定义对象,然后将对象直接赋给数组就行了。
public static void main(String[] args) {
student student = new student("张三",23);
student student1 = new student("李四",24);
student student2 = new student("王五",25);
student[] arr = new student[3];
arr[0] = student;
arr[1] = student1;
arr[2] = student2;
for (student Student : arr) {
System.out.println(Student);
}
输出结果是
student{name='张三', age=23}
student{name='李四', age=24}
student{name='王五', age=25}
//这就是一个对象数组
集合的由来
面向对象语言对事物的体现都是以对象的形式,所以为了方便对多个对象的操作,Java就提供了集合类。
数组和集合的区别
(1): 长度区别:
数组的长度是固定的而集合的长度是可变的
(2): 存储数据类型的区别:
数组可以存储基本数据类型 , 也可以存储引用数据类型; 而集合只能存储引用数据类型
(3): 内容区别:
数组只能存储同种数据类型的元素 ,集合可以存储不同类型的元素
Collection类的功能
方法名 | 功能 |
---|---|
boolean add(Object obj) | 添加一个元素 |
boolean addAll(Collection c) | 加一个集合的元素 (给一个集合添加进另一个集合中的所有元素) |
void clear() | 移除一个元素 |
boolean removeAll(Collection c) | 移除一个集合的元素,交集元素。没有交际则返回false |
boolean contains(Object o) | 判断集合中是否包含指定的元素 |
boolean containsAll(Collection c) | 判断集合中是否包含指定的集合元素(全包含才算包含 |
boolean isEmpty() | 判断集合是否为空 |
Iterator iterator() | 获取迭代器 |
int size() | 元素的个数 |
boolean retainAll(Collection c) | 获取两个集合的交集元素(交集:两个集合都有的元素) |
Object[] toArray() | 把集合转换为数组 |
框架的基本测试
public static void main(String[] args) {
Collection collection = new ArrayList();
collection.add(100);
collection.add(200);
collection.add(100);
collection.add(200);
System.out.println(collection);
boolean remove = collection.remove(300);
System.out.println(remove);
boolean remove1 = collection.remove(100);
System.out.println(remove1);
// collection.clear();
//System.out.println(collection);
boolean contains = collection.contains(200);
System.out.println(contains);
boolean empty = collection.isEmpty();
System.out.println(empty);
int size = collection.size();
System.out.println(size);
//这个将Collection中的各种功能都进行了测试
public static void main(String[] args) {
Collection collection = new ArrayList();
Collection collection1 = new ArrayList();
collection1.add(100);
collection1.add(200);
collection.add(100);
collection1.add(200);
// ((ArrayList) collection).addAll( collection1) ;
// System.out.println(collection);
// boolean b = collection1.removeAll(collection);
// System.out.println(b);
boolean b1 = collection1.containsAll(collection);
System.out.println(b1);
boolean b = collection1.retainAll(collection);
System.out.println(b);
}
//将Collection中的高级基本功能测试完毕,可以复制到JDK中进行测试,我使用的是JDK1.8.测哪个方法,将哪个方法从注释中释放
集合的遍历
1.集合转为数组开始遍历
2.
以下还有集合存储字符串,集合存储自定义对象等遍历就不介绍了
List类
List的概述
元素有序,并且每一个元素都存在一个索引.元素可以重复.
List的遍历与上述的方法一样,但是多了一个List自带的迭代器
listIterator()
ListIterator的特有功能
方法名 | 功能 |
---|---|
boolean hasPrevious(): | 是否存在前一个元素 |
E previous(): | 返回列表中的前一个元素 |
也可以用他来进行迭代枚举,和一般的迭代器类似
接下来我们用for来遍历一次集合
对了我们如果想要在遍历途中,修改集合,我么们只能用一般的for循环,用迭代器不行会报错,说并发修改异常
用迭代器遍历集合,在遍历一开始,迭代器就将原来的集合顺序和对应的元素记住了,你在修改的话,与他记忆产生偏差,所以就会报错
数据结构很基本的知识
数组和链表的区别
数组特点:查询快,增删慢
链表特点:查询慢,增删快
List三个子类的特点
ArrayList:
底层数据结构是数组,查询快,增删慢。
线程不安全,效率高。
Vector:
底层数据结构是数组,查询快,增删慢。
线程安全,效率低。
LinkedList:
底层数据结构是链表,查询慢,增删快。
线程不安全,效率高。
如何使用?
就要看做这个项目的需求是什么,然后来选用某个类