类集(Collection接口)干货!!
很多人对类集的概念不清楚? 其实很简单,类集就属于动态数组。由于数组长度是固定的,JDK1.2开始为了解决这种问题,提供了动态的数组实现框架——Java类集框架。
1. Collection集合接口
Collection接口中有两个重要方法:add()、iterator()。子接口都有这两个方法。
2.List接口(Collection子接口)
在实际开发之中,List接口的使用频率可以达到Collection系列的80%。在进行集合处理的时候,优先考虑List接口。
List子接口与Collection接口相比最大的特点在于其有一个get()方法,可以根据索引取得内容。由于List本身还是接
口,要想取得接口的实例化对象,就必须有子类,在List接口下有三个常用子类:ArrayList、Vector、LinkedList。
2.1 List允许保存重复数据
2.2List的get()操作
2.3 通过Collection进行输出处理
get()方法是List子接口提供的。如果现在操作的是Collection接口,那么对于此时的数据取出只能够将集合变为对象数组操作。
2.4 集合与简单Java类
在以后的实际开发中,集合里面保存最多的数据类型,就是简单Java类。
集合操作简单java类时,对于remove()、contains()方法需要equals()方法支持
class Person{
private String name;
private Integer age;
public Person(String name,Integer age){
this.name = name;
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 Objects.equals(name,person.name)&&
Objects.equals(age,person.age);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
public class Main{
public static void main(String[] args) {
List<Person> PersonList = new ArrayList<>();
PersonList.add(new Person("张三",20));
PersonList.add(new Person("李四",30));
PersonList.add(new Person("王五",40));
//集合类中contains(),remove()方法需要equals()的支持
PersonList.remove(new Person("李四",30));
System.out.println(PersonList.contains(new Person("王五",40)));
for(Person p:PersonList){
System.out.println(p);
}
}
运行结果:
2.5 旧的子类(Vector) 使用较少
Vector是从JDK1.0提出的,而ArrayList是从JDK1.2提出的。
2.6 2.4 linkedList子类
在List接口中还有一个LinkedList子类,这个子类如果向父接口转型的话,使用形式与之前没有任何区别。
3.Set集合接口
Set接口与List接口最大的不同在于Set接口中的内容是不允许重复的。同时需要注意的是,Set接口并没有对
Collection接口进行扩充,而List对Collection进行了扩充。因此,在Set接口中没有get()方法。
在Set子接口中有两个常用子类:HashSet(无序存储)、TreeSet(有序存储)