Collection framework generics

Posted by ranman on Tue, 01 Mar 2022 02:58:08 +0100

aggregate

A dynamic array whose length can be changed and any data type can be maintained

Interface

Interfacefunction
CollectionThe most basic interface and top-level interface of the collection framework
ListCollection's sub interface, orderly storage, non unique (repeatable elements) objects, and the most commonly used interface
SetCollection's sub interface, storing unordered, unique (non repeatable elements) objects
MapAnother interface independent of Collection, the top-level interface, stores a set of key value pairs, and provides key to value mapping
leratorThe interface of output set elements is generally applicable to unordered sets and output from front to back
ListteratorThe sub interface of the iterator can output the elements in the collection in both directions
EnumerationThe traditional output interface has been replaced by the iterator
SortedSetThe sub interface of Set can sort the elements in the Set
QueueQueue interface
Map.EntryThe internal interface of Map describes a set of key value pair elements stored in Map

Collection interface

The most basic parent interface can store a group of unordered and non unique objects
It is a sub interface of the Lterable interface

Common methods of Collection interface

methodfunction
int size()Get collection length
boolean isEmpty()Determine whether an object exists in the collection
Iterator iterator()Instantiate Iterator interface and traverse collection
Object[] toArray()Convert the collection into an Object array
T[] toArray(T[] a)Converts a collection to an array of the specified data type
boolean add(E e)Add elements to the collection
boolean reomove(Object o)Remove element from collection
boolean containsAll(Collection c)Determines whether all elements of another set exist in the set
boolean addAll(Collection c)Adds all elements of a collection to the collection
boolean removeAll(Collection c)Removes all elements of a collection from the collection
void clear()Clears all elements in the collection
boolean equals(Collection c)Judge whether two sets are equal
int hashCode()Returns the hash value of the collection

Collection sub interface

list: store ordered and non unique elements
Set: store unordered and unique elements
Queue: queue interface

List interface extension method

methodfunction
T get(int index)Returns the element at the corresponding position in the collection by subscript
T Set(int index, T elementStores an object at a specified location in the collection
int indexOf(Object o)Find the position of an object in the collection from front to back
int lastIndexOf(Object o)Find the position of an object in the collection from back to front
ListLterator ListLterator()Instantiate the ListLterator interface to traverse the List collection
List subList(int fromIndex, int toIndex)Intercept the List set by subscript

Implementation class of List interface

ArrayList: array based implementation, non thread safe, high efficiency, all methods are not synchronized
Vector: thread safety, low efficiency and thread safety are realized directly through the synchronized modification method
Stack: subclass of vector, which implements the data structure of stack and last in first out
LikedList: realize first in first out column matching and store in the form of linked list

Stack operation stack method

  • push: stack method
  • peek: take out the top element of the stack, copy a copy of the top of the stack, take it out, and the data structure in the stack remains unchanged after removal
  • pop: take out the top element of the stack, directly take out the top element of the stack, and subtract one from the data in the station after taking it

The difference between ArrayList and LikedList

The forms of memory storage are different. ArrayList adopts the form of array and LikedList adopts the form of linked list
The storage space of array in memory is continuous, fast to read and slow to add or delete
Because the array is continuous in memory, the data can quickly find the memory address of the target element through the addressing formula. Because the memory is continuous, adding or deleting elements must move the data. Moreover, the longer the array length is, the more elements need to be moved, so the operation is slower
The storage space of linked list in memory is discontinuous. It is slow to read and fast to add and delete
The linked list is discontinuous in memory. There is no fixed formula to use. To read, you can only traverse the target element from the first place. The larger the data scale, the slower the operation
Fast addition and deletion, because you only need to reset the post pointers of the two nodes before and after the target element, which is independent of the data scale

The difference between the pop method of LinkedList and Stack

The same point: both take out the first element in the set
Differences: the order of the two is opposite. Stack is the last in first out principle, so pop method takes out the last element. LinkedList is the first in first out principle, so pop method takes out the first element

Set

Set is the sub interface of Collection. Set stores data in the form of hash, so the elements are out of order and can store a group of unordered and unique data

Set common implementation classes

HashSet

Stores an unordered and unique set of objects
Unordered: the storage order of elements is inconsistent with the traversal order

public static void main(String[] args) {
        HashSet hashSet = new HashSet();

        hashSet.add("Hellol");
        hashSet.add("World");
        hashSet.add("xiaobo");
        hashSet.add("wyb");
        hashSet.add("xiaobo");

        System.out.println(hashSet);
        System.out.println("Length:" + hashSet.size());

        //ergodic
        Iterator iterator = hashSet.iterator();
        //The next cursor is true if it is not empty
        while (iterator.hasNext()){
            //Movement Cursor 
            System.out.println(iterator.next());
        }
    }

LinkedHashSet

Stores an ordered and unique set of elements
Order: the storage order of elements is consistent with the traversal order

public static void main(String[] args) {
        LinkedHashSet hashSet = new LinkedHashSet();

        hashSet.add("Hellol");
        hashSet.add("World");
        hashSet.add("xiaobo");
        hashSet.add("wyb");
        hashSet.add("xiaobo");

        System.out.println(hashSet);
        System.out.println("Length:" + hashSet.size());

        //ergodic
        Iterator iterator = hashSet.iterator();
        //The next cursor is true if it is not empty
        while (iterator.hasNext()){
            //Movement Cursor 
            System.out.println(iterator.next());
        }
    }

How does LinkedHashSet determine whether two objects are equal

First, it will judge whether the hashcodes of the two objects are equal
If they are not equal, they are not considered the same object
If they are equal, they are judged by equals, and equals is equal, then the two objects are equal, otherwise they are not equal

What is HashCode

The hashCode of the object is the hashCode that converts the internal information of the object into a hash value through a specific rule

TreeSet

Store an ordered and unique set of data
Order: all elements in the collection are automatically arranged in ascending order. No matter what the storage order is, they must be output in ascending order when traversing

public static void main(String[] args) {
        TreeSet treeSet = new TreeSet();
        treeSet.add(new Data(6));
        treeSet.add(new Data(5));
        treeSet.add(new Data(3));
        treeSet.add(new Data(4));
        treeSet.add(new Data(2));
        treeSet.add(new Data(6));
        treeSet.add(new Data(1));

        Iterator iterator = treeSet.iterator();
        while(iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }
    class Data implements Comparable{

    private int num;

    public Data(int num){
        this.num = num;
    }

    //instanceof determines whether it is a type
    //Object o is of type Data
    /**
     * Return value:
     * 1 Indicates that A is greater than B
     * 0 Indicates that A equals B
     * -1 Indicates that A is less than B
     */
    @Override
    public int compareTo(Object o) {
        if(o instanceof Data){
            Data data = (Data) o;
            if (this.num > data.num){
                return 1;
            }else if(this.num == data.num){
                return 0;
            }else{
                return -1;
            }
        }
        return 0;
    }
    @Override
    public String toString() {
        return "Data{" +
                "num=" + num +
                '}';
    }
}

Map

A Map can operate on a pair of elements because the Map storage structure is a key - value mapping/
The Map interface is defined using generics and defines two generics: K and V. K represents the Key and V represents the value

Common methods of Map

methoddescribe
int size()Get collection length
boolean isEmpty()Judge whether the set is empty
boolean containsKey(Object key)Determine whether a key exists in the set
boolean containsValue(Object value)Determine whether a value exists in the set
V get(Object key)Get the value corresponding to the key in the set
V put(K key,V value)Store a set of key value elements into the collection
V remove(Object key)Delete the value corresponding to the key in the collection
void putAll(Map map)Add another Map to the collection
void clear()Clear all elements in the collection
Set<k> keySet()Take out all the key s in the Set and return a Set
Collection<v> values()Take out all value s in the Collection and return a Collection
int hashCode()Gets the hash value of the collection
boolean equals(Object o)Compare two sets for equality

Implementation class of Map interface

hashMap

Store a set of elements that are unordered, key cannot be repeated, and value can be repeated
Non thread safe, high performance

hashtable

Store a set of elements that are unordered, key cannot be repeated, and value can be repeated
Thread safe, low performance

TreeMap

It stores a set of ordered elements whose key cannot be repeated and whose value can be repeated. It can be sorted by key

Collections utility class

It specifically provides some tool classes for manipulating Collections and Collections
Arrays tool class for arrays

Common methods of Collection tool class

methoddescribe
public static sort()Sort collection
public static int binarySearch(List list,Object v)To find the position of v in the list, the set must be ordered
public static get(List list,int index)Returns the value of the index position in the list
public static void reverse(List list)Output the list in reverse order
public static void swap(List list,int i,int j)Swaps two elements at a specified location in a collection
public static void fill(List list,Object obj)Replace all elements in the collection with obj
public static Object min(List list)Returns the minimum value in the collection
public static Object max(List list)Returns the maximum value in the collection
public static boolean replaceAll(List list,Object old,Object new)Replace old with new in the list set
public static boolean addAll(List list,Object... obj)Add elements to the collection

Object... Variable parameters

public static void test(Object... arg){

}  

Parameters can be any number, but the types must match

public static void main(String[] args) {
        ArrayList arrayList = new ArrayList();
        Collections.addAll(arrayList,
                            new Student(1,"Xiaobo",21),
                            new Student(2,"Xiao Zhang",22),
                            new Student(3,"Xiao Jin",24)
                );
        Collections.sort(arrayList);
        System.out.println(arrayList);
    }
class Student implements Comparable {

    private int id;
    private String name;
    private int age;

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

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
    @Override
    public int compareTo(Object o) {
        if (o instanceof Student) {
            Student student = (Student) o;
            if (this.age > student.age) {
                return -1;
            } else if (this.age == student.age) {
                return 0;
            } else {
                return 1;
            }
        }
        return 0;
    }
}

Generics

When defining a class, you do not specify the specific data type of the information in the class, but temporarily replace it with an ID. when the external instantiation object is used, you can specify the specific data type

Direct definition

public class A{
	private B b;
  
  public C test(D d){
    return new C();
  }
}

Generic definition

public class A<T,E,M>{
  private T b;
  public E test(M m){
    return E;
  }
}
A<B,C,D> a = new A();

Advantages of using generics

Greatly improve the flexibility of the program and the scalability of the class
It can refer to member variable type, parameter type of method and return value type of method

public class Time<H,M,S> {

    private H hour;
    private M minute;
    private S second;

    public H getHour() {
        return hour;
    }

    public void setHour(H hour) {
        this.hour = hour;
    }

    public M getMinute() {
        return minute;
    }

    public void setMinute(M minute) {
        this.minute = minute;
    }

    public S getSecond() {
        return second;
    }

    public void setSecond(S second) {
        this.second = second;
    }
}
public static void main(String[] args) {
        Time<Integer,Integer,Double> time = new Time<>();
        time.setHour(99);
        time.setMinute(11);
        time.setSecond(16.0);
        System.out.println("Now the time is:"+time.getHour() + "/" +
                                        time.getMinute() + ":" +
                                        time.getSecond()
                );
    }

Generic wildcard

?: Indicates that any generic type object can be used to make it universal
Polymorphism is not applicable in generics

public static void main(String[] args) {

        ArrayList<String> list1 = new ArrayList<>();
        list1.add("xiaobo");

        ArrayList<Integer> list2 = new ArrayList<>();
        list2.add(21);

        getList(list1);
        getList(list2);
    }

    public static void getList(ArrayList<?> arrayList){
        System.out.println(arrayList);
    }

Upper and lower bounds of generics

upper limit

Instantiate a specific data type, which can be a subclass of the upper bound type or the upper bound type itself, represented by extends, class name < generic ID extends upper bound class name >

public class T<M> {

    public static void main(String[] args) {

        test(new T<Integer>());
        test(new T<Float>());
        test(new T<Double>());

    }

    public static void test(T<? extends Number> t){
        System.out.println(t);
    }
  }

lower limit

Instantiate a specific data type, which can be the parent of the lower bound type or the lower bound type itself, and use super to represent the class name < generic ID super lower bound class name >

public class T<M> {

    public static void main(String[] args) {

        test2(new T<Object>());

    }

    public static void test2(T<? super String> t){
        System.out.println(t);
    }
  }

generic interface

public interface MyInterface<T> {
    public T getValue();
}

Implementation classes continue to use generic identifiers when defining

public class MyInterfaceImpl implements MyInterface<T>  {

    private T obj;

    public MyInterfaceImpl(T obj) {
        this.obj = obj;
    }

    @Override
    public T getValue() {
        return this.obj;
    }
}

The implementation class directly gives the specific data type when defining

public class MyInterfaceImpl2 implements MyInterface<String> {

    private String obj;

    public MyInterfaceImpl2(String obj) {
        this.obj = obj;
    }

    @Override
    public String getValue() {
        return this.obj;
    }
}

The right start, small progress, and then continue, hey, I'm Xiaobo, take you to see the world I can see

Topics: Java