"Java Core Technology" Reading Notes (2)-Generics, Collections

Generic programming

Generic programming means that the code can be reused by many different types of objects.
Providing type parameters solves the safety and readability problems of forced conversion in inherited programming

basic concept

class

Generic class: A class with one or more type variables.
Definition: public class Pair
type variable specifies the return type of the method and the types of domain and local variables

  • E collection element type
  • Types of keywords and values ​​of K and V tables
  • T / U / S any type

Generic types can be instantiated by replacing type variables with concrete types, and generic classes can be regarded as factories of ordinary classes

method

Definition: public static T getMiddle (T ... a)
Call: ArrayAlg.getMiddle (<type parameter> can be omitted, the compiler will infer it by itself, and sometimes it will prompt an error)

Type limit

A class or method constrains type variables to
indicate that T is a subtype of the bound type

A type variable or wildcard can have multiple type qualifications:
T extends Comparable & Serializable
(at most one class in the qualification)

principle

Type erasure

For the virtual machine, the compiler provides the corresponding primitive type (the name after the type parameter is deleted), erased perameter type, and replace it with a restricted type (unrestricted type variables use Object, multiple restricted ones use the first, the label interface should be Put behind the limit)

Translation generic method

Problems caused by method erasure (the subclass inherits the parent class of the generic method):

  1. Type erasure conflicts with polymorphism
    Resolution: Compiler synthesis bridge method (calling new parameter type method of subclass in method)
  2. The problem of stricter return type is
    solved: the compiler synthesizes the bridge method (virtual machine, the parameter type and the return type are used to determine a method, the compiler generates byte code with only two methods with different return types, and the virtual machine can correctly handle )

Example: DateInterval extends Pair, override setSecond, getSecond method
Use: javac command to compile DateInterval class, and then execute javap -private DateInterval command to decompile, you can see the bridge method synthesized by the compiler.

Note: Other applications of the bridge method-you can specify a stricter return type when overriding the method.

Translation generic expression

When a method calls and accesses a generic domain, the compiler inserts a mandatory type conversion.

Calling legacy code may produce a warning, you can use the annotation @SuppressWarnings ("unchecked") to make it disappear

summary

  • There are no generics in the virtual machine, only ordinary classes and methods.
  • All type parameters are replaced with their qualified types.
  • The bridge method is synthesized to maintain polymorphism.
  • In order to maintain type safety, mandatory type conversion is inserted when necessary.

Use restrictions

Mostly caused by type erasure

  1. You cannot instantiate type parameters with basic types
  2. Run-time type queries only apply to primitive types
  3. Cannot create an array of parameterized types (declaring variables is legal)
    type erasure, may add unrelated instances of different types of parameters to the same array, causing internal logic errors
  4. varargs warning
    The method with a variable number of parameters is passed in an instance of a generic type. The rules are relaxed, but you will be warned that you need to add @SafeVarargs or @SuppressWarnings
  5. Cannot instantiate type variables
    Solution: static Pair makePair (Supplier constr) or Class.newInstance ()
  6. Cannot construct a generic array
    • If the array is only used as the private instance domain of the class, it can be declared as Object [] and forced conversion is performed when obtaining the element
    • The user provides an array constructor expression
      public static <T extends Comparable> T [] minmax (IntFunction constr, T… a) {T port mm = constr.apply (2);}
      String [] :: new
      or usage: Array.newInstance
      application: ArrayList.toArray
  7. Invalid type variable in static context of generic class
  8. Cannot throw or catch generic class instances
  9. Can eliminate the inspection of the checked abnormality
  10. Note the conflict after erasure
    • Note the method naming
    • "If you want to support the conversion of erasure, you need to force a class or type variable not to be a subclass of two interface types at the same time, and these two interfaces are different parameterizations of the same interface."

Inheritance rules

  1. No matter what connection S has with T, usually, Pai has no connection with Pair.
  2. Can convert parameterized types to primitive types
  3. Generic classes can extend or implement other generic classes

Wildcard type

concept

When using generics, the generic type that allows the parameter type to change is called the wildcard type

public static void printBuddies (Pair p) is
not allowed to pass Pair to this method, but after modifying the parameter to
Pair <? extends Employee>

Classified by limitation


  1. Subtype- qualified variables of type Pair <? Extends Employee> are not allowed to call its setFirst method, and the compiler refuses to pass any particular type
    to distinguish between safe accessor methods and unsafe changer methods.

  2. Supertype-qualified subtype bound
    can provide parameters for the method, but can not use the return value

  3. Unqualified wildcard
    does not require actual type

Wildcard capture

Wildcard capture is only legal if there are many restrictions

Reflection and generics

Generic Class

It allows ClaSS method's return type of more targeted
T newInstanceO
T Cast (Object obj)
T getEnumConstants ()
Class <? Super T> getSuperclass ()
Constructors getConstructor (C1ass ... parameterTypes)
Constructors getDeclaredConstructor (Class ... parameterTypes)

Information in the virtual machine

Generic reflection-related classes in virtual machines
TypeVariable: Type variable
WildcardType: Wildcard qualified
ParameterizedType: Generic class or interface type (such as Comparable <? Super T>)
GenericArrayTYpe: Generic array type

set

Collection framework

basic structure

Iterable
Iterator: hasNext, next, remove, forEachRemaining
Collection: add, iterator, generic utility method
AbstractCollection: provides the default implementation of some methods

Collection framework interface

List interface: defines multiple methods for random access
ListIterator: defines a method for adding elements in front of the iterator
RandomAccess: label interface, identifies whether the collection implementation class supports efficient random access method
Set interface: equivalent to Collection, but Not all sets are collections, it is convenient for programmers to write methods that only accept sets.
SortedSet, SortedMap: defines a method to get a subset view of the collection. (9.4)
NavigableSet, NavigableMap: methods for searching and traversing ordered sets and maps, TreeSet, TreeMap implementation

Specific collection

Specific collection in Java library
Concrete collection inheritance structure

  1. Linked
    lists The major drawback of arrays and array lists: inserting or deleting elements in the middle will pay a great price (the only reason to use linked lists).
    All linked lists are actually double linked. The ListIterator interface defines the reverse operation method

    • Adding elements The
      position-dependent add method is the responsibility of the iterator. It makes sense to use the iterator to add elements to a naturally ordered collection. All add methods are defined in the ListIterator
      to insert elements forward or backward. The number of insertion positions is n +1
    • Traversal
      Reverse traversal: hasPrevious, previous
      Do not use random access method to traverse the linked list, the efficiency is extremely low
    • Delete You
      can delete forward or backward
  2. Array list

  3. Hash Set The
    load factor determines when to re-hash the hash table. More than 75% of the positions in the table have been filled with elements, the table will automatically re-hash
    HashSet with double the number of buckets : based on the hash table set
    JavaSE8, when the bucket is full, the binary tree will be balanced from the linked list programming

  4. Tree set
    TreeSet is an ordered collection (Sorted Collection) using a tree structure to complete the sort (the current implementation uses a red-black tree), realized NavigableSet.
    When there is no need to sort the elements in the set, the hash set is preferred.

  5. Queue
    Retrieval rule: first-in first-out
    Implementation: cyclic array, linked list
    ArrayDeque: limited bounded collection capacity
    LinkedList: unbounded collection

  6. Priority queues
    are inserted in any order, retrieved in sorted order, and the remove method is called to always get the element with the lowest priority in the current queue.
    Iteratively process elements without sorting.
    Use structure: heap
    Usage example: task scheduling

Map

  1. Common implementation class
    HashMap
    TreeMap

  2. Operation
    put-returns the last value stored with this key parameter
    update map
    counts.put (word, counts.getOrDefault (word, 0) + 1);
    or
    counts.putlfAbsent (word, 0);
    counts.put (word, counts .get (word) + 1); // Now we know that get will succeed
    or
    counts.merge (word, 1, Integer :: sum);

  3. Map view
    keySet, values, entrySet
    can delete elements, can not call add to add elements

  4. Private mapping

  • WeakHashMap: When the only reference to the key comes from the hash entry, this data structure will work with the garbage collector to delete the key / value pair.
  • LinkedHashSet and LinkedHashMap:
    ① When the entry is inserted into the table, it will be merged into the doubly linked list, remember the order of the inserted items.
    ② The link hash map can use the access order to iterate over the mapping entries. Each time get or put is called, the affected entry will be deleted from the current position and placed at the end of the linked list of entries, LinkedHashMap <K, V> (initialCapacity, loadFactor, true)
    ③ The removeEldestEntry method can be overridden to implement the “based on access order "Least Recently Used" principle to achieve caching
  • EnumSet, EnumMap: The keys are enumerated types, and the set can be constructed using static methods
  • IdentityHashMap: System.identityHashCode calculation key, use == when comparing objects

Views and wrappers

  1. Lightweight collection wrapper
    Arrays.asList ()
    Collection.nCopies (100, "xx")
    Collection.singleton () / singletonList / singletonMap

  2. Sub-range
    can apply any operation

  3. Can not be modified
    Collections.unmodifiableCollection / xxxList / xxxSet ......

  4. Synchronize

  5. Checked view When
    adding an element, check whether it meets the defined generic type

algorithm

  1. Sort
  2. Binary search
  3. Simple algorithms
    min, max, ...
  4. Batch operations
    addAll, retainAll, ...
  5. Array conversion

Legacy collection

Legacy collection

  1. Hashtable
  2. Enumeration
  3. Properties mapping
  4. Stack
  5. BitSet

summary

This article sorts out the contents of generics and collections in Java core technology. The implementation of generics in Java is the function of the compiler. Type erasure is done where generics are defined, and forced type conversions are inserted where generics are used to avoid In order to solve the problem of too many class definitions, the security of the Java language is enhanced; the collection framework provides a rich interface and implementation classes, and the function development, and reflects the specific application of generics.

Welcome to pay attention to my public account to learn more:
My public account

Published 159 original articles · praised 225 · 210,000 views

Guess you like

Origin blog.csdn.net/lyg673770712/article/details/104559479