Java collection system (a) - Collection System

1, Java collection system

  Java collection system consists of two main interfaces derive out: Collection and Map. This blog is mainly about the inheritance hierarchy Collection, Collection is an interface that defines a set of collection methods of operation, its implementation class is mainly rewrite abstract methods and define their own specific way. The system implementation classes are direct or indirect Collection of three sub-interfaces: List, Queue, Set. We used to achieve the main class ArrayList, LinkedList, TreeSet, HashSet.
Collection system inheritance tree

2, List interface and its implementation class

2.1、List

List interface following main methods:
public void the Add (int index, E Element): The specified element to a specified position in the set on.
public E get (int index): Returns the specified element in the collection position.
public E remove (int index): removing the element position specified in the list, return the removed element.
public E set (int index, E element): Replace elements in the collection specified location with the specified element, the element returns the value before the update.

        //1.使用多态思想,创建List集合对象
        List<String> list = new ArrayList<>();
        //2.往尾部添加制定元素
        boolean a = list.add("小明");
        boolean b = list.add("小红");
        boolean c = list.add("小刚");
        //3.输出集合
        System.out.println("list = " + list);
        //4.删除指定索引的元素,并返回被删除的元素
        String removeElement = list.remove(2);
        System.out.println("removeElement = " + removeElement);
        //5.获取指定位置的元素
        String getElement = list.get(1);
        System.out.println("getElement = " + getElement);
        //6.修改指定位置的元素
        String setElement = list.set(1, "小严");
        System.out.println("setElement = " + setElement);

2.2、ArrayList

  ArrayList collection of stored data structure is an array (on the difference between an array and a linked list, consult the data structure). Elemental additions and deletions slow and look for fast, everyday use in the most developed capabilities for query data through the data, it is the most common ArrayList collection. ArrayList want to understand, you should view its source code.
  View source understood, class defines private static final int DEFAULT_CAPACITY = 10; and private int size; wherein DEFAULT_CAPACITY represents an initial capacity of 10, size indicates the number of data currently stored list. Class has multiple constructors, if specified capacity, then the specified number created ArrayList, otherwise the default number of 10 initial capacity.
  Some other common methods can understand the use according to the method name and parameter list, if you want to learn to view the source code.

2.3、LinkedList

  LinkedList set of data is stored in a linked list structure. Elemental additions and deletions quick look slow.
Here Insert Picture Description
  The actual development of a set of elements are added and deleted often involve the operation from beginning to end, while LinkedList provides a number of methods of operation from beginning to end.
public void addFirst (E e): The beginning of the specified element into this list.
public void addLast (E e): the specified element to the end of this list.
public E getFirst (): returns the first element in this list.
public E getLast (): Returns the last element in this list.
public E removeFirst (): Removes and returns the first element of this list.
public E removeLast (): Removes and returns the last element of this list.
public E pop (): this list stack represented by the pop-up element.
public void push (E e): The list element is pushed into the stack represented.
public boolean isEmpty (): If the list does not contain the element, it returns true.
  The specific structure and method of the LinkedList, we can use it to define the stacks and queues, specific codes are as follows

public class Stack<E> {
    //定义一个linkedlist集合
    private LinkedList<E> list = new LinkedList<>();

    //入栈,链表的头为栈顶
    public void push(E e) {
        list.addFirst(e);
    }

    //出栈,并返回被出栈的元素
    public Object pop() {
        E e = list.removeFirst();
        return e;
    }

    //栈的大小
    public int size() {
        return list.size();
    }

    //查看栈顶元素
    public E peak(){
        return list.getFirst();
    }

	//集合是否为空
    public boolean isEmpty(){
        int size = this.size();
        if (size == 0){
            return true;
        }
        return false;
    }

    public String toString(){
        return list.toString();
    }
}
public class Quene<E> {
    private LinkedList<E> list = new LinkedList<>();

    //入队,链表的头为队头
    public void push(E e) {
        list.addLast(e);
    }

    //出队
    public E pop() {
        return list.removeFirst();
    }

    //队列的大小
    public int size() {
        return list.size();
    }

    //查看队头元素
    public E peak(){
        return list.getFirst();
    }

    //查看队尾元素
    public E rear(){
        return list.getLast();
    }

    //队列是否为空
    public boolean isEmpty(){
        int size = this.size();
        if (size == 0){
            return true;
        }
        return false;
    }

    public String toString(){
        String s = list.toString();
        return s;
    }
}

3, Set interface and its implementation class

3.1、Set

   Set List interfaces and interfaces, same as inherited from the Collection interface, its methods and the Collection interface are basically the same, and no expansion of the Collection interface function, but more stringent than the Collection interface. The difference is that with the List interface, Set interface elements of disorder, and some rules will ensure non-duplication into the elements. Set a collection of multiple sub-categories, here we introduce HashSet them, LinkedHashSet two sets.

3.2、HashSet

   java.util.HashSet is an implementation of the Set interface, its stored element is not repeatable, and (i.e., inconsistent access sequence) elements are disordered. View source shows that to achieve the underlying HashSet is actually a HashMap support, but the value of which is fixed, as the key value of HashSet. HashSet is (Detail View data structure) according to a hash algorithm to determine the storage location of the object within the collection, and it has good access and search performance. The only way to ensure the elements depends on: hashCode and equals method. To understand HashSet, you should use HashSet each store type Integer, String types, custom object types to study HashSet.

public static void main(String[] args) {
        HashSet<Integer> set = new HashSet<Integer>();
        set.add(1);
        set.add(3);
        set.add(2);
        set.add(1);
        System.out.println("set = " + set);
    }

Outputs the result to set = [1, 2, 3], described disordered added element is not repeated.

public static void main(String[] args) {
        HashSet<String> set = new HashSet<>();
        String s1 = new String("aaa");
        String s2 = new String("aaa");
        System.out.println(s1 == s2);//false
        String s3 = new String("ccc");
        String s4 = new String("ddd");
        set.add(s1);
        set.add(s2);
        set.add(s3);
        set.add(s4);
        System.out.println("set = " + set);
    }

Outputs the result to set = [aaa, ccc, ddd]. Since String type is a reference type, the s1 and s2 is different from the address, but the override equals method String, HashSet so that the two are the same.

public class Student {
    //未重写equals和hashCode方法
    private int age;     //
    private String name;      //

    public Student(int age, String name) {
        this.age = age;
        this.name = name;
    }
    @Override
    public String toString() {
        return "Student{" +
                "age=" + age +
                ", name='" + name + '\'' +
                '}';
    }

	public static void main(String[] args) {
        HashSet<Student> set = new HashSet<>();
        Student stu1 = new Student(23, "小明");
        Student stu2 = new Student(23, "小明");
        Student stu3 = new Student(24, "小红");
        set.add(stu1);
        set.add(stu2);
        set.add(stu3);
        System.out.println("set = " + set);
    }
}

  Student override equals no defined method, the student HashSet determines whether two objects are the same (original equals method of Object class) values are identical to the address determined. Therefore, the resulting output is set = [Student {age = 23 , name = ' Bob'}, Student {age = 23 , name = ' Bob'}, Student {age = 24 , name = ' red'}].
  IDEA generated using equals and hashCode method, the result is set = [Student {age = 23 , name = ' Bob'}, Student {age = 24 , name = ' red'}].

3.3、LinkedHashSet

  We know that the only HashSet guarantee element, but the element is not stored into the order, then we have to ensure the orderly, how to do it? In a subclass HashSet a LinkedHashSet below, it is a data storage structure list and combined hash table, to ensure access to the same. Other uses almost identical HashSet.

3.4、TreeSet

  TreeSet underlying binary tree, the element may be ordered, but needs to implement a custom class interfaces comparable rewrite COMPARATO () method. TreeSet can guarantee the uniqueness of object elements (not necessarily guaranteed to be unique, needs to be determined according to the method of overwriting compaaTo). The following demo store integer types and custom object types.

public static void main(String[] args) {
        TreeSet<Integer> set = new TreeSet<>();
        set.add(1);
        set.add(2);
        set.add(3);
        set.add(5);
        set.add(1);
        set.add(4);
        System.out.println("set = " + set);
    }

Result output set = [1, 2, 3, 4, 5]

public class Student implements Comparable{
    private int age;     //
    private String name;      //

    public Student(int age, String name) {
        this.age = age;
        this.name = name;
    }

    @Override
    public String toString() {
        return "Student{" +
                "age=" + age +
                ", name='" + name + '\'' +
                '}';
    }

    @Override
    public int compareTo(Object o) {
        Student student = (Student)o;//向下转型
        return this.age - student.age;//按年龄排序
    }

    public static void main(String[] args) {
        TreeSet<Student> set = new TreeSet<>();
        set.add(new Student(23, "小明"));
        set.add(new Student(24, "小明"));
        set.add(new Student(25, "小明"));
        System.out.println("set = " + set);
    }
}

4、Queue

Queue is a queue of class, but now very small. The focus is on the List and Set

Please indicate the wrong place! Thought that it was in trouble if you can give a praise! We welcome comments section or private letter exchange!

Published 30 original articles · won praise 72 · views 10000 +

Guess you like

Origin blog.csdn.net/Orange_minger/article/details/104554670