------- android培训、java培训、期待与您交流! ----------
这篇文章主要分析List集合、Set集合和Map集合的特点,以及它们之间的区别。文章第一章分析List集合的特点、第2章分析Set集合的特点,第3章分析Map集合的特点,最后总结,分析这三者之间的区别。
1. List集合
List集合的特点是:元素是有序的,并且元素可以重复,因为该集合体系有索引。
1.1 List子类的区别和特点
在List集合中,有3个子类:ArrayList、LinkedList和Vector,它们使用的数据结构和特点如下图所示:
1.2 List集合常用的共性方法
不论是ArrayList、LinkedList还是Vector,它们都有共性的方法,如下图(只列举其中一部分):
1.3 ArrayList集合存储对象元素——去除重复元素
List集合中,可以出现相同的元素。现在,希望ArrayList集合中存储的元素不能出现相同元素,不是相同的元素才能添加进来,相同的元素则不让添加进来。需求如下。
需求:有一个Student类,该有有两个成员变量name和age,现在将Student存储到ArrayList集合中,name和age相同的视为同一个元素,相同元素在ArrayList集合中只能出现一份,也就是集合中不能出现相同的元素。
我们知道,ArrayList集合是可以存储相同元素的,那么要实现只能存储不同的元素,该如何实现呢?
解决方法是:在Student类中定义一个equals方法,该方法覆写了Object的equals方法,在equals中定义规则,当Student对象的name和age属性值都相同时,则视为是同一个元素。并在主函数中定义一个静态的singleElement方法,该方法接收ArrayList集合对象作为参数。在singleElement方法中遍历传入的ArrayList对象中的所有元素,并调用调用ArrayList对象的contains方法,判断是否集合中已经存在某个元素,如果存在则不添加该元素进来。
简而言之,该方法就是:创建两个ArrayList集合对象,第一个集合存储Student对象,该集合存储的Student对象存在相同元素;然后定义一个singleElement静态方法,该方法接收第一个ArrayList集合对象作为实参。然后在singleElement方法中创建一个新的ArrayList集合对象(下面称为第二个集合),在singleElement方法中变量第一个集合中的元素,当某个元素在第一个集合中不存在,则将该元素插入到第二个集合中,存在的则不插入,最后返回第二个集合给第一个集合,这样就实现的上面的需求。
代码:
package com.itheima.entranceExam.blog;
import java.util.ArrayList;
import java.util.Iterator;
//Student类
class Student {
private String name;
private int age;
//构造方法
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
//覆盖equals方法
@Override
public boolean equals(Object obj) {
// 如果传入的参数不是Student对象
if (!(obj instanceof Student))
return false;
Student stu = (Student) obj;
//name和age相同,则认为是同一个元素
return (this.name.equals(stu.name)) && (this.age == stu.age);
}
}
//主函数
public class ArrayListTest {
//去除相同元素的方法
public static ArrayList<Object> singleElement(ArrayList<Object> al) {
ArrayList<Object> arrayList = new ArrayList<>();
Iterator<Object> it = al.iterator();
while(it.hasNext()) {
Object obj = it.next();
//如果不包含该元素,则添加进来,contains() 方法底层调用的是 Person 的 equals() 方法
if(!arrayList.contains(obj))
arrayList.add(obj);
}
//返回新的没有重复元素的ArrayList集合对象
return arrayList;
}
public static void main(String[] args) {
//创建ArrayList集合对象
ArrayList<Object> al = new ArrayList<Object>();
//创建Student对象,并将对象添加到ArrayList集合中
al.add(new Student("Steve", 23));
al.add(new Student("Steve", 23));
al.add(new Student("Larry", 21));
al.add(new Student("Gates", 26));
//调用去除重复元素的方法
al = singleElement(al);
//迭代ArrayList集合中的元素
Iterator<Object> it = al.iterator();
while(it.hasNext()) {
Student stu = (Student) it.next();
System.out.println(stu.getName()+" "+stu.getAge());
}
}
}
输出结果如下图: