Dynamic Reference Storage - Set & Precise Set Definition - Generics

Posted by lancia on Fri, 23 Aug 2019 13:48:19 +0200

Preface:

For object-oriented languages, in order to operate more than one object conveniently, it is necessary to store the object.

The biggest problem with using arrays to store objects is the fixity of array length. (inflexible, difficult to expand)

Java collections, also known as containers, can dynamically store references to objects in containers. (Flexible and extensible)


Set and array distinction

Array:

  • You can store the same basic data type or reference data type

  • Length Fixed


Collection:

  • Different types of elements can be stored, but they must be reference data types
  • Variable length


Overview of collections

Java collection classes are mainly derived from Collection and Map. Collection is an interface, a highly abstracted collection, which contains the basic operations and attributes of the collection; Map is a mapping interface, that is, key-value key-value pairs.


Collection

  • List orderly repeatable
    • ArrayList
    • LinkedList
    • Vector
    • Stack
  • Set disorder is not repeatable
    • HashSet
    • LinkedSet
    • TreeSet


ArrayList - LinkedList - Vector- Stack features

  • ArrayList: Asynchronous, thread insecurity, high efficiency of execution; the bottom use of arrays, storage and reading efficiency, insertion and deletion efficiency is low
  • LinkedList: Asynchronous, bi-directional linked list, insertion and deletion efficiency
  • Vector: Synchronization, thread safety, low execution efficiency
  • Stack: Inherit Vector

From the perspective of data growth:

Array List and Vector use arrays to control objects in collections.

When you add elements to both types, if the number of elements exceeds the current length of the internal array, they all need to extend the length of the internal array.

Vector automatically doubles the array length by default, and ArrayList is 50% of the original.

So if you want to save a lot of data in a collection, there are some advantages to using Vector.


HashSet-LinkedSet-TreeSet Features

HashSet is implemented by HashMap, which has strong access and search performance.

LinkedHashSet inherits HashSet.

TreeSet provides an implementation of storing Set interfaces using tree structure. Objects are stored in ascending order, and access and traversal time is very fast. The bottom layer is TreeMap.


Map

  • HashMap
  • TreeMap


HashMap - TreeMap features

HashMap is usually faster than TreeMap (because of the data structure of trees and hash tables). It is recommended to use HashMap more often than TreeMap when sorting is needed.

HashMap results are not sorted, while TreeMap outputs are sorted.


Common methods of Collection interface and Iterator interface



Simple use:


1.HashSet

import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;

public class Main {

    public static void main(String[] args) {

        Date currentDate =  new Date();

        HashSet hs= new HashSet();
        //Adding elements
        hs.add(currentDate.toString());
        hs.add(new String("2"));
        hs.add("3");


        hs.add("3");//Cannot contain duplicate elements, automatically overwritten

        System.out.println("for Iterative output");
        
        for(Object element:hs)
        {System.out.println(element); }

        System.out.println("Iterator Iterative output");
        
        Iterator iterator=hs.iterator();
        while(iterator.hasNext())
        {
            System.out.println(iterator.next());
        }
        //Delete elements
        hs.remove("2");
        hs.remove(currentDate.toString());

        System.out.println("After deleting the element, output:");
        
        for(Object element:hs)
        {
            System.out.println(element);
        }

}

}


2.TreeSet

//TreeSet default automatic sorting

import java.util.TreeSet;
import java.util.Iterator;
public class Main {
    public static void main(String args[]) {
        TreeSet tr = new TreeSet();
        tr.add("B");
        tr.add("A");
        tr.add("D");
        tr.add("E");
        System.out.println("Direct Output Set Objects");

        System.out.println(tr);

        System.out.println("for Ergodic output");
        for (Object element : tr) {
            System.out.println(element);
        }
        System.out.println("Iterator Iterative output");
        Iterator iterator = tr.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }
}


3.LinkedList

import java.util.LinkedList;
import java.util.Iterator;
public class Main
{
public static void main(String []args)
{
        LinkedList li= new LinkedList();

        li.addFirst("C");
        li.addLast("D");
        li.addFirst("B");
        li.addLast("E");
        li.addFirst("A");
        li.addLast("F");

        System.out.println( "Direct Output");
        System.out.println(li);
        System.out.println("--------------------");

        System.out.println( "use for output");
        for(Object str:li)
        {System.out.println(str);}
        System.out.println("--------------------");

        System.out.println( "Using Iterator Output");
        Iterator iterator= li.iterator();
        while(iterator.hasNext())
        {System.out.println(iterator.next());}
        System.out.println("--------------------");


        System.out.println("Visit");
        System.out.println("peekFirst:"+li.peekFirst());//getFirst,getLast
        System.out.println("peekLast:"+li.peekLast());

        System.out.println("delete");
        System.out.println(li.removeFirst());//pollFirst,pollLast
        System.out.println(li.removeLast());
        System.out.println("--------------------");


        System.out.println("use for output");
        for(Object str:li)
        {System.out.println(str);}
        System.out.println("--------------------");
        }
}


4.ArrayList

import java.util.ArrayList;
import java.util.Iterator;
public class Main
{
public static void main(String []args)
{
        ArrayList  list = new ArrayList();
        list.add("A");//Appends the specified element to the end of this list
        list.add(1,"B");//Point location of insert list
        list.add("C");
        list.add("D");
        list.add("E");
        //for traversal
        System.out.println("for ergodic");
        for(Object element:list)
        {
        System.out.println(element);
        }
        System.out.println("------------------");
        //Iterator traversal
        //Obtaining iterators
        System.out.println("Iterator traversal");
        Iterator  iterator = list.iterator();
        //If there are still elements that can be iterated, return true.
        while(iterator.hasNext())
        {
        System.out.println(iterator.next());//      Returns the next element of the iteration.
        }
        System.out.println("------------------");
        //Delete element remove
        System.out.println("Before deletion:");
        for(Object element:list)
        {
        System.out.println(element);
        }
        list.remove(0);
        list.remove(2);
        System.out.println("------------------");
        System.out.println("After deletion:");
        for(Object element:list)
        {
        System.out.println(element);
        }
}
}


5.HashMap

import java.util.HashMap;
public class Main
{
    public static void main(String []args)
    {
        HashMap hs = new HashMap<>();
        //Write data
        System.out.println("Write data...");
        System.out.println("...");
        hs.put(1,"Huachenyu");
        hs.put(2,"Jay Chou");
        hs.put(3,"Liu Ruoying");
        hs.put(4,"Xu Song");
        //Read data
        System.out.println("Read data...");
        System.out.println("...");
        System.out.println(hs.get(1));
        System.out.println(hs.get(2));
        System.out.println(hs.get(3));
        System.out.println(hs.get(4));
        //Delete data
        System.out.println("...");
        System.out.println("Delete data...");
        hs.remove(1);
        System.out.println(hs.get(1));
    }
}


Summary:

There are many kinds of implementations of collections, but one thing remains unchanged. The main function of collections is to store and manipulate objects. The correct way to open collections is to cooperate with specific application scenarios according to the storage mode and operation performance characteristics of specific implementations.



Problems caused by set universality

When an element is dropped into a collection, the collection is compiled into an Object class for better generality.

The resulting problems:

  • Exceptions saved by different objects to the same specified set
  • Mandatory Type Conversion Exceptions Caused by Extracting Elements from a Collection


What is generics?

Parametric type!!!
What is a parameterized type???
Specific types (such as String, Integer) are abstracted into parameters.


The role of generics

  • Eliminates mandatory type conversions in collections and reduces exceptions.
  • The restricted type of object is specified, and the type security of Java is realized.
  • Merge code. Increase reuse rate.


The manifestation of generics

Rhombic grammar:

List<String> list = new List<>();
Map<Integer , String > = new Map<>();


generic class

//generic class
public class Main<T>
{
    private T data;
    public Main(T data)
    {
        this.data=data;
    }
    public T getData()
    {
        return data;
    }
    public static void main(String []args)
    {
        Main<Integer> g1 = new Main<Integer>(1222);
        System.out.println(g1.getData());

        Main<Double> g2 = new Main<Double>(1222.1222);
        System.out.println(g2.getData());

        Main<String> g3 = new Main<String>("cat");
        System.out.println(g3.getData());

    }
}



generic method

public class Main
{
    public static <E> void printArray(E inputArray[])
    {
        for(E element:inputArray)
        {
            System.out.printf("%s",element);
        }
    }

    public static void main(String args[])
    {
        Integer intArray[]= {1,2,3,4,5};
        Double doubleArray[]= {1.1,2.2,3.3,4.4,5.5};
        Character charArray[]= {'A','B','C'};

        System.out.printf("The integer array is:\n");
        printArray(intArray);
        System.out.printf("\n");


        System.out.printf("The double precision array is:\n");
        printArray(doubleArray);
        System.out.printf("\n");

        System.out.printf("The character array is:\n");
        printArray(charArray);
        System.out.printf("\n");

    }

}

generic interface

public interface TestInterface<T> {
    public T next();
}
import java.util.Random;

public class Main implements TestInterface<String>
{
    String list[]={"L","A","C"};
    @Override
    public String next()
    {
        Random rand = new Random();
        return list[rand.nextInt(2)];
    }
    public static void main(String[] args)
    {
        Main obj = new Main();
        System.out.println(obj.next());
    }
}

Topics: Java