java高级之集合
文章目录
概述
- 万事万物皆对象,我们可以使用数组来存储对象但存在一些弊端。
- 集合就像是一种java容器,可以动态的存储多个对象,可以把它理解为是动态的数组。
- 集合框架包含三大块内容:对外的接口、接口的实现和对集合运算的算法。
集合 VS 数组
数组
- 数组存储的数据有序、可重复;
- 数组初始化以后,长度确定,不可变,不易扩展;
- 数组声明的类型,元素初始化时的类型便确定;
- 数组中提供的属性和方法少,不便于进行添加、删除、插入等操作,效率不高;无法直接获取存储元素的个数。
集合
- 长度可变;
- 可以存储不同的数据类型。
整体概述
-
Collection
接口,理解为单列集合,存储对象时以单个来存储。 -
Map
接口:理解为双列集合,用来存储一对(key - value)一对的数据。
Collection接口
常用方法
Collection
接口常用方法总结。
方法返回值 | 方法名 | 方法的描述 |
---|---|---|
boolean |
add(Object e) |
添加单个元素 |
boolean |
addAll(Collection c) |
指定集合的元素添加到此集合 |
int |
size() |
获取集合中的元素个数。 |
void |
clear() |
清空集合 |
boolean |
isEmpty() |
判断该集合是否为空 |
boolean |
contains(Object o) |
判断是否包含该元素 |
boolean |
containsAll(Collection c) |
判断是否包含指定集合 |
boolean |
remove(Object o) |
通过equals()方法找到指定的第一个元素并删除 |
boolean |
removeAll(Collection<?> c) |
删除指定集合在本集合中的元素 |
boolean |
retainAll(Collection<?> c) |
取交集, c中存在的元素 |
boolean |
equals(Object o) |
判断集合是否相等,元素都相同时才相等 |
int |
hashCode() |
返回此集合的哈希码值。 |
Object[] |
toArray() |
返回一个包含此集合中所有元素的数组。 |
Iterator<E> |
iterator() |
返回迭代器对象 |
-
代码试验如下:
@Test public void test1(){ Collection collection = new ArrayList(); //1、add(Object e) 添加单个元素 collection.add("AA"); collection.add(new Student("张三",24)); Collection collection1 = new ArrayList(); collection1.add("BB"); collection1.add("CC"); //2、addAll(Collection c) 指定集合的元素添加到此集合 collection.addAll(collection1); //3、size() 获取集合中的元素个数 collection.size(); //打印一下该集合 System.out.println(collection); //4、clear() 清空集合 //collection.clear(); //5、isEmpty() 判断集合是否为空 System.out.println("集合是否为空:"+collection.isEmpty()); //6、boolean contains(Object o); 判断是否包含该元素 System.out.println(collection.contains("AA")); //如果不重写equals()和hashcode()方法,会是false System.out.println(collection.contains(new Student("张三",24))); //7、boolean containsAll(Collection c) 判断是否包含指定集合 System.out.println(collection.containsAll(collection1)); //8、boolean remove(Object o),通过equals()方法找到指定的第一个元素并删除 collection.remove("AA"); //9、boolean removeAll(Collection coll) 删除指定集合在本集合中的元素 collection.removeAll(Arrays.asList("BB","CC")); //打印一下该集合 System.out.println(collection); collection.add("AA"); collection.add("BB"); collection.add("CC"); //10、boolean retainAll(Collection c) 取交集 collection.retainAll(Arrays.asList("BB","CC