1. Why use generic (generic) programming?
In Java Core technology: The code written can be reused by many different types of objects, allowing interoperability between generic and legacy code.
Two concepts mentioned: type parameter , wildcard type
The explanation in Head first Java seems more understandable: almost all programs written in generics are related to working with collections, although generics can be used elsewhere, but the main purpose is to let you write a collection of type safety This means that the compiler can help prevent you from adding dog to a group of cat.
As stated in the Sort method of the collection class: public static <t extends comparable<?super t>>void sort (list<t> list) where Comparable<?super t> is the restriction on the type of the parameter, what object is added, and whether the object is returned or referenced.
Before a generic feature appears, the compiler can't notice what you're adding to the collection, because all the collections are written in the Object type, and you can put anything in the ArrayList, something like arraylist<object>
The use of the <> this set of symbols in Java programs or files means that generics are working-it's a trait that starts with Java 5.0.
ArrayList Although it is the most commonly used, but occasionally there are special circumstances, such as ArrayList There is no sorting method. Here are a few important:
LinkedList: A highly efficient set designed to often insert or delete intermediate elements (actually ArrayList is more practical)
TreeSet: maintaining and preventing duplication in an orderly state
(the element of TreeSet must be comparable
With TreeSet, one of the following must be true
The elements in the collection must be of a type that implements comparable
Using overloads, take the constructor of the comparator parameter to create the TreeSet
)
HashSet: Prevents duplicate collections and can quickly find matching elements. (But to override the two methods of Hashcode () and Equals ()
HashMap: Available in pairs for Name/value to be saved in the extraction
LinkedhashMap: Similar to HashMap, but remembers the order in which elements are inserted, and can be set to sort by the last access of the element.
About generics
1) Create an instance of a generic class (for example, ArrayList)
When you create a ArrayList, you have to specify the objects it allows, just like an array of simple arrays.
New Arraylist<song> ()
2) Declaring a variable with a specified generic type
What happens to multi-state encounters with generic types?
Arrays and ArrayList
For ArrayList, if the method is declared as fetching Arraylist<animal>, it takes the wisdom to take arraylist< Animal > Parameters,arraylist< Animal sub-class > On the line, and arrays can be implemented.
The type of the array is checked during run time, but the type checking of the collection only occurs during compilation, so if there is a type error, the compilation will fail for the collection.
Generics and polymorphism
Universal characters? : A method to accept the parameters of the animal sub-type
public void Takeanimals (arraylist<? extends animal> animals) {...
}
Extends also represents inheritance and implementation
List<song> songlist=new arraylist<song> ()
1) declaring (and invoking) a method of taking a generic type
Disclaimer: void foo (list<song> List)
Call X.foo (songList)
Summary: The main is the generic class, generic variables, generic methods.
Note: The API design team already covers most of the amount of data structures you will encounter, and almost only the collections really need generics.
Classes that use generics
ArrayList is the most common type of generics, and we'll start by looking at its documentation.
public class Arraylist<e> extends abstraction<e> implements LIST<E> {
......
}
where e is called the type parameter
Methods of using Generics
The generic class represents the declaration of the class with the type parameter, and the generic method represents the method's declaration characteristics with the type parameter
There are several different ways of using type parameters in a method:
1) Use the type parameter defined in the class declaration
public class arraylist<e> extends Abstraclist<e> {
Public boolean Add (E o)
2) Use a type parameter that is not defined in the class declaration
Public <t extends animal> void takething (arraylist<t> list)
Represents the incoming animal or its subtypes to out-initialize the ArrayList.
from Collection the API in the documentation we found 3 a primary interface: List , Set and Map
LIST: A good helper to deal with the order
is a collection that knows the index position, and the list knows the position of something in the collection, and can have multiple elements referencing the same object.
SET: Focus on the unique nature
Duplicate collections are not allowed. It knows if something already exists in the collection, and there are not multiple elements referencing the same object
MAP: An expert searching with key
Use paired key values and data values. Map maintains values associated with key, two keys can refer to the same object, but key cannot be duplicated, a typical key is a string, but it can be any object.
Collection of APIs
The above comes from head first Java, and the next content from the Java core technology (feeling the book is a little abstract)
Generic programming is divided into 3 levels of competency:
1) use only generic classes
2) can use Java generic system to solve the code cohesion, generic class mixing problem.
3) Implement your own generic classes and generic methods.
2. Generic class : A class that has one or more type variables.
The pair class introduces a type variable t, enclosed in angle brackets <>, and placed behind the class name.
A generic class can have more than one type variable, for example, you can also define a pair class, where the first and second fields use different types:
public class pair<t,u>{...}
3. Generic method:
Here's a simple way to define a type parameter:
Class Arrayalg
{
public static <T> t Getmiddle (t ... a)
{
return A[A.LENGTH/2];
}
}
The type variable is placed after the modifier public static and returns the front of the type.
A generic method can be defined in a normal class or in a generic class.
4. Qualification of type variables
Implement an interface for a type variable to achieve a qualifying purpose, avoiding compilation errors, such as implementing the comparable interface for T
public static <t extends comparable> t Getmiddle (t ... a)
Type erase: Remove the restriction of the type variable, or replace the type variable with an object
Bridge method: To solve the problem of type erasure and polymorphism conflict
Facts about the Java Generics transformation:
Virtual machines do not have generics, only ordinary classes and methods.
All parameter types are replaced with their qualified type
The bridge method is synthesized to maintain polymorphism
To preserve type safety, insert a forced type conversion if necessary
"Learning Notes" Java Basics-Generics and collections