Collection集合类

常用集合类的继承结构如下: 
Collection(接口)<–List(接口)<–Vector 
Collection(接口)<–List(接口)<–ArrayList 
Collection(接口)<–List(接口)<–LinkedList 
Collection(接口)<–Set(接口)<–HashSet(实现类) 
Collection(接口)<–Set(接口)<–HashSet(实现类) <–LinkedHashSet (实现类) 
Collection(接口)<–Set(接口)<–SortedSet(接口)<–TreeSet(实现类) 
Map(接口)<–SortedMap(接口)<–TreeMap(实现类) 
Map(接口)<–HashMap(实现类)
Collection 
|–List 
有序(存储顺序和取出顺序一致),可重复 
|–Set 
无序(存储顺序和取出顺序不一致,但它有自己的存储顺序),唯一

牢记: 
ArrayXxx:底层数据结构是数组,查询快,增删慢 
LinkedXxx:底层数据结构是链表,查询慢,增删快 
HashXxx:底层数据结构是哈希表。依赖两个方法:hashCode()和equals() 
TreeXxx:底层数据结构是二叉树。两种方式排序:自然排序和比较器排序

  • HashSet内存图解

引用块内容

  • TreeSet内存图解

引用块内容

LinkedList(链表)数据存储 
  链表不是基于数组的,所以不受数组性能的限制。 
它每一个节点(Node)都包含两方面的内容: 
  1.节点本身的数据(data); 
  2.下一个节点的信息(nextNode)。 
所以当对LinkedList做添加,删除动作的时候就不用像基于数组的ArrayList一样,必须进行大量的数据移动。只要更改nextNode的相关信息就可以实现了,这是LinkedList的优势。

package com.java.LinkedList;

import java.util.LinkedList;

/*
List 接口的链接列表实现。实现所有可选的列表操作,并且允许所有元素(包括 null)。
除了实现 List 接口外,LinkedList 类还为在列表的开头及结尾 get、remove和 insert元素
提供了统一的命名方法。这些操作允许将链接列表用作堆栈、队列或双端队列。

void addFirst(E e) 将指定元素插入此列表的开头。
void addLast(E e) 将指定元素添加到此列表的结尾。  

E getFirst() 返回此列表的第一个元素。 
E getLast() 返回此列表的最后一个元素。 

E removeFirst() 移除并返回此列表的第一个元素。 
E removeLast() 移除并返回此列表的最后一个元素。 
*/

public class LinkedListDemo {
    public static void main(String[] args) {
        LinkedList link=new LinkedList<>();

        link.add("hello");
        link.add("world");
        link.add("java");

        link.addFirst("android");
        link.addLast("last");

        link.removeFirst();
        link.removeLast();

        System.out.println("link:"+link);

        System.out.println("link.getFirst="+link.getFirst());
        System.out.println("link.getLast="+link.getLast());
    }
}

HashSet数据存储 
必须同时重写hashCode()和equals()两个方法,才能使相同属性的对象具有相同哈希值。

package com.java.Set;

import java.util.HashSet;

public class HashSetDemo {
    public static void main(String[] args) {
        HashSet<Student> hs=new HashSet<Student>();

        Student s1=new Student("林青霞",27);
        Student s2=new Student("柳岩", 22);
        Student s3=new Student("王祖贤", 30);
        Student s4=new Student("林青霞", 20);
        Student s5=new Student("范冰冰", 22);
        Student s6=new Student("林青霞", 27);

        hs.add(s1);
        hs.add(s2);
        hs.add(s3);
        hs.add(s4);
        hs.add(s5);
        hs.add(s6);

        for(Student s:hs){             System.out.println(s.toString());         }     } }