1.集合简介
集合、数组都是对多个数据进行存储操作的结构,简称Java容器。
说明:此时的存储,主要指的是内存层面的存储,不涉及到持久化的存储(.txt,.jpg,.avi,数据库中)
Collection接口:单列集合,用来存储一个一个的对象
List接口:存储有序的、可重复的数据。
ArrayList、LinkedList、Vector
Set接口:存储无序的、不可重复的数据
HashSet、LinkedHashSet、TreeSet
Map接口:双列集合,用来存储一对(key - value)一对的数据
HashMap、LinkedHashMap、TreeMap、Hashtable、Properties
2.数组的优缺点
2.1 数组在存储多个数据方面的特点:
一旦初始化以后,其长度就确定了。
数组一旦定义好,其元素的类型也就确定了。我们也就只能操作指定类型的数据了。
比如:String[] arr;int[] arr1;Object[] arr2;
2.2 数组在存储多个数据方面的缺点:
一旦初始化以后,其长度就不可修改。
数组中提供的方法非常有限,对于添加、删除、插入数据等操作,非常不便,同时效率不高。
获取数组中实际元素的个数的需求,数组没有现成的属性或方法可用
数组存储数据的特点:有序、可重复。对于无序、不可重复的需求,不能满足。
正因为数组存取数据存在缺点,数组的长度一旦确定就不能修改,在存取数据的长度不定时,我们需要用到Java集合
3.Collection接口方法使用
向Collection接口的实现类的对象中添加数据obj时,要求obj所在的类要重写equals()
add(Object e):将元素e添加到集合collection中
size()获取添加的元素的个数
addAll(Collection coll1) :将coll1集合中的元素添加到当前的集合中
clear():清空集合元素
isEmpty():判断当前集合是否为空
示例如下:
@Test
public void test1(){
Collection coll = new ArrayList();
//add(Object e):将元素e添加到集合collection中
coll.add("AA");
coll.add("BB");
coll.add(123); //自动装箱
coll.add(new Date());
//size()获取添加的元素的个数
System.out.println(coll.size()); //4
//addAll(Collection coll1) :将coll1集合中的元素添加到当前的集合中
Collection coll1 = new ArrayList();
coll1.add("HH");
coll1.add(120);
coll.addAll(coll1);
System.out.println(coll.size());
System.out.println(coll1.size());
System.out.println(coll1);
System.out.println(coll);
//clear():清空集合元素
coll.clear();
//isEmpty():判断当前集合是否为空
System.out.println(coll.isEmpty());
System.out.println(coll1.isEmpty());
}
contains(Object obj)判断当前集合中是否包含obj,判断时会调用obj对象所在类的equals()方法。
containsAll(Collection coll1):判断形参coll1中的所有元素是否都存在于当前集合中,只有都存在于当前集合中才能返回 true,只要有一个不在就返回 false
示例如下:
@Test
public void test1(){
Collection coll = new ArrayList();
coll.add(123);
coll.add("AA");
coll.add(new String("haha"));
coll.add(false);
coll.add(new Person("heihei",26));
//contains(Object obj)判断当前集合中是否包含obj,判断时会调用obj对象所在类的equals()方法
boolean contains = coll.contains(123);
System.out.println(contains); //true
System.out.println(coll.contains(new String("haha"))); //true
System.out.println(coll.contains(new Person("heihei",26))); //本来是false,修改后为true
//在Person类中重写equals()方法后,再执行上条语句运行结果会变成true
System.out.println(coll.contains(new Person("heihei",26)));//true
//containsAll(Collection coll1):判断形参coll1中的所有元素是否都存在于当前集合中,
// 只有都存在于当前集合中才能返回true,只有要一个不在就返回false
Collection coll1 = Arrays.asList(123,"AA");
System.out.println(coll.containsAll(coll1));//true
}
remove(Object obj):从当前集合中移除obj元素,移除成功返回true,失败返回false。
removeAll(Collection coll1):从当前集合中移除coll1中所有的元素,(当前集合中两者共有的元素)
示例如下:
@Test
public void test2(){
Collection coll = new ArrayList();
coll.add(123);
coll.add("AA");
coll.add(new String("haha"));
coll.add(false);
coll.add(new Person("heihei",26));
//remove(Object obj):从当前集合中移除obj元素,移除成功返回true,失败返回false
System.out.println(coll.remove(123)); //true
System.out.println(coll); //[AA, haha, false, Person{name='heihei', age=26}]
System.out.println(coll.remove(1234)); //false
coll.remove(new Person("heihei",26));
System.out.println(coll); //[AA, haha, false]
//removeAll(Collection coll1):从当前集合中移除coll1中所有的元素,(当前集合中两者共有的元素)
System.out.println("************");
Collection coll1 = Arrays.asList(false,"BB");
System.out.println(coll); //[AA, haha, false]
System.out.println(coll.removeAll(coll1)); //true
System.out.println(coll); //[AA, haha]
System.out.println(coll1); //[false, BB]
}
retainAll(Collection coll1):获取当前集合和coll1集合中共有的元素,并返回给当前集合。
示例如下:
@Test
public void test3(){
Collection coll = new ArrayList();
coll.add(123);
coll.add("AA");
coll.add(new String("haha"));
coll.add(false);
coll.add(new Person("heihei",26));
//retainAll(Collection coll1):获取当前集合和coll1集合中共有的元素,并返回给当前集合
System.out.println(coll); //[123, AA, haha, false, Person{name='heihei', age=26}]
Collection coll1 = Arrays.asList(123,"BB",456);
coll.retainAll(coll1);
System.out.println(coll); //[123]
System.out.println(coll1); //[123, BB, 456]
}
equals(Object obj):判断当前集合和形参集合元素是否都相同,有顺序的如果两者的元素都一样,但是顺序不一样,结果还是false,因为ArrayList是有序的
示例如下:
@Test
public void test4(){
Collection coll = new ArrayList();
coll.add(123);
coll.add("AA");
coll.add(new String("haha"));
coll.add(false);
coll.add(new Person("heihei",26));
Collection coll1 = new ArrayList();
coll1.add(123);
coll1.add("AA");
coll1.add(new String("haha"));
coll1.add(false);
coll1.add(new Person("heihei",26));
//equals(Object obj):判断当前集合和形参集合元素是否都相同,有顺序的
//如果两者的元素都一样,但是顺序不一样,结果还是false,因为ArrayList是有序的
System.out.println(coll.equals(coll1)); //true
}
hashCode():返回当前对象的哈希值。
toArray():集合--->数组。
示例如下:
@Test
public void test5(){
Collection coll = new ArrayList();
coll.add(123);
coll.add("AA");
coll.add(new String("haha"));
coll.add(false);
coll.add(new Person("heihei",26));
//hashCode():返回当前对象的哈希值
System.out.println(coll.hashCode()); //-217720878
//toArray():集合--->数组
Object[] arr = coll.toArray();
for(int i= 0;i
System.out.println(arr[i]);
/*
打印结果为:
123
AA
haha
false
Person{name='heihei', age=26}
*/
}
//拓展:数组--->集合:调用Arrays类的静态方法asList()
System.out.println("**************");
List list = Arrays.asList(new String[]{"AA","BB","HH"});
System.out.println(list); //[AA, BB, HH]
//下面的方法使用时要注意,可能会出错,会识别为一个元素。
List arr1 = Arrays.asList(new int[]{123,456});
System.out.println(arr1.size()); //1
System.out.println(arr1); //[[I@22927a81]
//可以按照下面的方式写
List arr2 = Arrays.asList(new Integer[]{123,456});
System.out.println(arr2.size()); //2
System.out.println(arr2); //[123, 456]
}
集合元素的遍历,使用迭代器Iterator接口
内部的方法:hashNext() 和next()搭配使用。
集合对象每次调用iterator()方法都得到一个全新的迭代器对象,默认游标都在集合的第一个元素之前。
内部定义了remove(),可以在遍历的时候,删除集合中的元素,此方法不同于集合直接调用remove()。
示例如下:
@Test
public void test1(){
Collection coll = new ArrayList();
coll.add(123);
coll.add("AA");
coll.add(new String("haha"));
coll.add(false);
coll.add(new Person("heihei",26));
Iterator iterator = coll.iterator();
//方式一:
// System.out.println(iterator.next());
// System.out.println(iterator.next());
// System.out.println(iterator.next());
// System.out.println(iterator.next());
// System.out.println(iterator.next());
// //报异常:java.util.NoSuchElementException
// System.out.println(iterator.next());
//方式二:
// for(int i=0;i
// System.out.println(iterator.next());
// }
//方式三:推荐使用
//hasNext():判断是否还有下一个元素
while(iterator.hasNext()){
System.out.println(iterator.next());
//在调用next()时,①指针下移,②将下移以后集合位置上的元素返回
/*
打印结果为:
123
AA
haha
false
Person{name='heihei', age=26}
*/
}
}
测试Iterator中的remove()
如果还未调用next()或在上一次调用next()方法后已经调用了remove()方法,再调用remove都会报异常:java.util.NoSuchElementException
@Test
public void test2(){
Collection coll = new ArrayList();
coll.add(123);
coll.add("AA");
coll.add(new String("haha"));
coll.add(false);
coll.add(new Person("heihei",26));
//删除集合中的haha元素
Iterator iterator = coll.iterator();
while (iterator.hasNext()){
Object obj = iterator.next();
if("haha".equals(obj)){
iterator.remove();
}
}
Iterator iterator1 = coll.iterator();
while(iterator1.hasNext()){
System.out.println(iterator1.next());
/*
打印结果为:
123
AA
false
Person{name='heihei', age=26}
*/
}
}
上述用到的Person类:
public class Person {
private String name;
private int age;
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return age == person.age &&
Objects.equals(name, person.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
}
4.List接口常用方法
void add(int index, Object ele):在index位置插入ele元素
boolean addAll(int index, Collection eles):从index位置开始将eles中的所有元素添加进来
Object get(int index):获取指定index位置的元素
示例如下:
@Test
public void test1(){
ArrayList list =new ArrayList();
list.add(123);
list.add(456);
list.add("AA");
list.add(456);
list.add(new Person("haha",26));
System.out.println(list); //[123, 456, AA, 456, Person{name='haha', age=26}]
//void add(int index, Object ele):在index位置插入ele元素
list.add(1,"BB");
System.out.println(list); //[123, BB, 456, AA, 456, Person{name='haha', age=26}]
//boolean addAll(int index, Collection eles):从index位置开始将eles中的所有元素添加进来
List list1 = Arrays.asList(1, 2, 3);
list.addAll(list1);
System.out.println(list.size()); //9
System.out.println(list); //[123, BB, 456, AA, 456, Person{name='haha', age=26}, 1, 2, 3]
//Object get(int index):获取指定index位置的元素(下标从0开始)
System.out.println(list.get(1)); //BB
}
int indexOf(Object obj):返回obj在集合中首次出现的位置
int lastIndexOf(Object obj):返回obj在当前集合中末次出现的位置
Object remove(int index):移除指定index位置的元素,并返回此元素
Object set(int index, Object ele):设置指定index位置的元素为ele
List subList(int fromIndex, int toIndex):返回从fromIndex到toIndex位置的子集合
示例如下:
@Test
public void test2(){
ArrayList list =new ArrayList();
list.add(123);
list.add(456);
list.add("AA");
list.add(456);
list.add(new Person("haha",26));
//int indexOf(Object obj):返回obj在集合中首次出现的位置,如果不存在返回-1
int index = list.indexOf(456);
System.out.println(index); // 1
int index1 = list.indexOf(4567);
System.out.println(index1); // -1
//int lastIndexOf(Object obj):返回obj在当前集合中末次出现的位置,如果不存在返回-1
System.out.println(list.lastIndexOf(456)); //3
//Object remove(int index):移除指定index位置的元素,并返回此元素
System.out.println("*************");
Object obj= list.remove(0);
System.out.println(list); //[456, AA, 456, Person{name='haha', age=26}]
System.out.println(obj); //123
// Object set(int index, Object ele):设置指定index位置的元素为ele
System.out.println("**************");
list.set(2,"HH");
System.out.println(list); //[456, AA, HH, Person{name='haha', age=26}]
// List subList(int fromIndex, int toIndex):返回从fromIndex到toIndex位置的左闭右开的子集合
System.out.println("**************");
List subList = list.subList(2, 4);
System.out.println(list); //[456, AA, HH, Person{name='haha', age=26}]
System.out.println(subList); //[HH, Person{name='haha', age=26}]
}
遍历 示例如下:
@Test
public void test3(){
ArrayList list =new ArrayList();
list.add(123);
list.add(456);
list.add("AA");
list.add(new Person("haha",26));
//方式一:Iterator迭代器
Iterator iterator = list.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
/*
打印结果为:
123
456
AA
Person{name='haha', age=26}
*/
}
//方式二:foreach循环
System.out.println("************");
for(Object obj :list){
System.out.println(obj);
/*
打印结果为:
123
456
AA
Person{name='haha', age=26}
*/
}
//方式三:普通for循环
System.out.println("************");
for(int i=0;i
System.out.println(list.get(i));
/*
打印结果为:
123
456
AA
Person{name='haha', age=26}
*/
}
}
区分List中remove(int index)和remove(Object obj)
@Test
public void testListRemove() {
List list = new ArrayList();
list.add(1);
list.add(2);
list.add(3);
updateList(list);
System.out.println(list);
}
private void updateList(List list) {
//list.remove(2); //此时对应的打印结果为[1, 2]
list.remove(new Integer(2)); //此时对应的打印结果为[1, 3]
}
总结:常用方法
增:add(Object obj)
删:remove(int index) / remove(Object obj)
改:set(int index, Object ele)
查:get(int index)
插:add(int index, Object ele)
长度:size()
遍历:① Iterator迭代器方式
② foreach循环
③ 普通for循环
5.Set接口常用方法
Set接口中没有额外定义新的方法,使用的都是Collection中声明过的方法。
向Set(主要指:HashSet、LinkedHashSet)中添加的数据,其所在的类一定要重写hashCode()和equals()
写的hashCode()和equals()尽可能保持一致性:相等的对象必须具有相等的散列码
Set:存储无序的、不可重复的数据
以HashSet为例说明:
1. 无序性:不等于随机性。存储的数据在底层数组中并非按照数组索引的顺序添加,而是根据数据的哈希值决定的。
2. 不可重复性:保证添加的元素按照equals()判断时,不能返回true.即:相同的元素只能添加一个。
HashSet底层:数组+链表的结构。
示例如下:
@Test
public void test1(){
Set set = new HashSet();
set.add(147);
set.add(258);
set.add("AA");
set.add("CC");
set.add(new User("jj",20));
set.add(123);
Iterator iterator = set.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
/*打印结果为:
AA
CC
258
147
User{name='jj', age=20}
123
*/
}
}
LinkHashSet的使用
LinkedHashSet作为HashSet的子类,在添加数据的同时,每个数据还维护了两个引用,记录此数据前一个数据和后一个数据
优点:对于频繁的遍历操作,LinkedHashSet效率高于HashSet
@Test
public void test2(){
Set set = new LinkedHashSet();
set.add(147);
set.add(258);
set.add("AA");
set.add("CC");
set.add(new User("jj",20));
set.add(new User("jj",20));
set.add(123);
Iterator iterator = set.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
/*打印结果为:
147
258
AA
CC
User{name='jj', age=20}
123
*/
}
}
TreeSet的使用
1.向TreeSet中添加的数据,要求是相同类的对象。
2.两种排序方式:自然排序(实现Comparable接口) 和 定制排序(Comparator)
3.自然排序中,比较两个对象是否相同的标准为:compareTo()返回0.不再是equals().
4.定制排序中,比较两个对象是否相同的标准为:compare()返回0.不再是equals().
示例一:
@Test
public void test1(){
TreeSet ts = new TreeSet();
//失败:不能添加不同类的对象
// ts.add(147);
// ts.add(369);
// ts.add("HHH");
// ts.add(new User("ll",23));
ts.add(147);
ts.add(258);
ts.add(369);
ts.add(123);
ts.add(-66);
Iterator iterator = ts.iterator();
while(iterator.hasNext()) {
System.out.println(iterator.next());
/*
打印结果为:按照从小到大的顺序排序
-66
123
147
258
369
*/
}
}
示例二:
@Test
public void test2(){
TreeSet ts = new TreeSet();
ts.add(new User("Tom",12));
ts.add(new User("Haha",32));
ts.add(new User("Gu",2));
ts.add(new User("Li",65));
ts.add(new User("Merry",33));
ts.add(new User("Haha",13));
ts.add(new User("Haha",66));
Iterator iterator = ts.iterator();
while(iterator.hasNext()) {
System.out.println(iterator.next());
/*
打印结果如下:
User{name='Gu', age=2}
User{name='Haha', age=13}
User{name='Haha', age=32}
User{name='Haha', age=66}
User{name='Li', age=65}
User{name='Merry', age=33}
User{name='Tom', age=12}
*/
}
}
示例三:
@Test
public void test3(){
Comparator comp = new Comparator() {
//按照年龄从小到大排列,年龄相同的就舍弃
@Override
public int compare(Object o1, Object o2) {
if(o1 instanceof User && o2 instanceof User){
User u1 = (User) o1;
User u2 = (User) o2;
return Integer.compare(u1.getAge(),u2.getAge());
}else{
throw new RuntimeException("输入的数据类型不匹配");
}
}
};
TreeSet ts = new TreeSet(comp);
ts.add(new User("Tom",12));
ts.add(new User("Haha",32));
ts.add(new User("Gu",12));
ts.add(new User("Li",65));
ts.add(new User("Merry",33));
ts.add(new User("Haha",13));
ts.add(new User("Haha",66));
Iterator iterator = ts.iterator();
while(iterator.hasNext()) {
System.out.println(iterator.next());
/*
打印结果如下:
User{name='Tom', age=12}
User{name='Haha', age=13}
User{name='Haha', age=32}
User{name='Merry', age=33}
User{name='Li', age=65}
User{name='Haha', age=66}
*/
}
}
上述使用到的User类如下:
public class User implements Comparable{
private String name;
private int age;
public User() {
}
public User(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return age == user.age &&
Objects.equals(name, user.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
//按照姓名从小到大排列,年龄从小到大排列
@Override
public int compareTo(Object o) {
if(o instanceof User){
User user= (User)o;
// return this.name.compareTo(user.name);
int compare = this.name.compareTo(user.name);
if(compare != 0){
return compare;
}else {
return Integer.compare(this.age,user.age);
}
}else {
throw new RuntimeException("输入的数据类型不匹配");
}
}
}
6.比较 ArrayList、LinkedList、Vector三者的异同?
同:都实现了List接口,存储数据的特点相同:存储有序的、可重复的数据。
异:ArrayList:作为List接口的主要实现类,线程不安全的,执行效率高,底层使用Object[] elementData存储。
LinkedList:对于频繁的插入、删除操作,使用此类效率比ArrayList高,因为底层使用双向链表存储
Vector:作为List接口的古老实现类,线程安全的,执行效率不高,底层使用Object[] elementData存储。