Java Collections and generics

Source: Internet
Author: User

First, set (collections)

Java uses collections to organize and manage objects.

1. The collection Class of Java

The collection class is primarily responsible for saving, holding, and managing objects, so the collection class is also known as a container class.

The collection class is divided into set, List, map and queue four systems.

    • Set represents unordered, non-repeating set;
    • The List represents an ordered, repeatable set;
    • Map represents a collection of elements with a mapping relationship;
    • Queue team to implement advanced first-out management of elements.

Arrays are also a collection class, which is one of the most efficient ways to store and access reference sequences randomly, and arrays are a good choice when it comes to efficient data access.

2. Set and generics

All collection classes are in the Java.util package, and only references to objects are saved in the collection. The collection class regards the elements it contains as an instance of object, which is convenient but also problematic, that is, multiple types of different elements are put into a collection, which increases the difficulty of type conversion when the collection is accessed, and even generates errors.

The introduction of generics improves this situation by using generics to constrain the type of elements in the collection and to let the collection remember the type of the element. This allows the compiler to check the element type that joins the collection, avoiding errors with inconsistent value types.

3. Introduction to the Java Collection framework

A collection framework is a unified schema used to represent and manipulate collections, and contains interfaces and classes that implement collections.

The entire collection framework of Java is designed around a standard set of interfaces that developers can use directly with the standard implementations of these interfaces, or they can implement custom collection implementation classes using the collection framework interface.

The design of the collection frame should meet three goals:

    • Performance. Ensure the efficiency of the algorithm implementation.
    • Interoperability.
    • High scalability. It is simple to extend a collection, just to implement a specific interface.

  

4. The Java Collection Framework organizes and manages objects in a unified manner, encompassing 3 aspects:

    • Interface. An interface defines the behavior specification of a collection operation, which forms a high-level view of the collection.
    • The implementation class. is the specific representation of the collection interface. Essentially, it is a reusable data structure.
    • Algorithm. Implements the algorithms commonly used in collection operations, such as searching and sorting. These algorithms are implemented in many States, i.e. the same method has different implementations on similar interfaces.

5. Set interface

The collection framework defines a set of interfaces that affirm the actions that can be performed on a particular type of collection.

The Java Collection class is primarily derived from two interfaces-Collection and Map, which are the root interfaces of the Java Collection framework.

6. Collection Class

The standard collection class implements the collection interface, some of which are abstract classes, implement some interfaces, and others are concrete classes that can be used directly in the code.

All classes that implement the collection interface must provide two standard constructors:

    • Parameterless constructor--used to create an empty collection;
    • Use collection as the constructor for the parameter--to create a new collection to replicate.

Ii. Generics (generics)

Generics Allow types (classes, interfaces) to be arguments when classes, interfaces, and methods are defined, and declared type parameters are replaced with specific types when used.

Generics are primarily applied in the collection framework.

1. Why generics are used

    • Improve the type safety of the program; the use of generics allows the compiler to validate type assumptions.
    • Helps avoid (forcing) transformation, allowing the compiler to discover transformation errors at compile time without waiting for the runtime
    • Universal algorithms can be implemented

  

2. Generic type

Definitions and declarations for generic classes:

The class name is followed by a <> to specify the name of one or more type parameters, as well as the value range of the type parameter, separated by commas between multiple type parameters.

 Public class matrix<t>{    ...}

Use of generics:

After you define the type parameters, you can use the type parameters almost anywhere in the class (except static blocks, static properties, static methods). Note that the type parameters defined by the parent class cannot be inherited by the quilt class.

/* instantiating a generic class */ Matrix<Float> ft=new matrix<float> ();

3. Generic method

Methods can also be generalized, regardless of whether the class that defines them is generic.

Why would you want to use a generic method instead of adding type T to the class definition?

    • When a generic method is static, the class's type parameter cannot be used.
    • When the type constraint on T is local to the method, this means that no constraints of the same type T are used in another method signature of the class. The type parameters of a generic method are local and can simplify the signature of the enclosing type.

Declaring a generic method:

 public <T> T IfThenElse (boolean  B, t first, T second) {    return b? First : Second;}

A generic class is a concrete type that indicates a generic when the class is instantiated, and the generic method indicates the specific type of the generic when the method is called.

The compiler allows the following code to be invoked using type inference to infer the type of T and replace T with the actual parameter:

String s=ifthenelse (b, "A", "B"), Integer inewnew Integer (2));

4. Type limitation

Sometimes we need to limit the range of type parameters.

Type wildcard character (? ,matrix<?> represents an arbitrary generic type.

/* indicates that add () can accept parameters of any generic type.  */publicvoid Add (matrix<?> m);

In this case, the type of argument that the Add () can accept is too broad. Developers may want to limit the specific types of parameters, such as those that only want to accept the type of number and its subclasses, rather than the variables of the type random, locale, and so on. This will limit the wildcard character.

such as the Matrix class, using the type parameter T, we have the number class as the upper bound of the type to limit this type parameter:

/* indicates that the type of parameter contained in the matrix is number and its subclasses */  Public class extends Numbers>{...}

When a type upper bound is introduced, the method defined in the type upper bound class (number) can be used when the type is used.

Similarly, we can use the number class as the lower bound of a type:

/* indicates that the type of parameter contained in the matrix is number and its parent class */  Public class Super Number>{...}

 

5, type erase (type Erasure)

Generics are implemented at the compiler level and do not contain generic type information in the generated byte code.

The type parameters that are added with generics are removed by the compiler at compile time, a process known as type erasure. That is, the type information attached by generics is not visible to the JVM.

The compiler finds possible errors at compile time, but still cannot avoid the case of a type conversion exception at run time.

Procedure for type erasure:

First, find the specific class that is used to replace the type parameter. If the upper bound of the type parameter is specified, the upper bound is used.

Then, the type parameter in the code is replaced by the specific type, and the occurrence of the type declaration, that is, the content of <>;

If you understand the type erasure, you will understand that the compiler takes all of the type checking work . The compiler prohibits the use of certain generics in order to ensure the security of the type.

Many generic features are related to type erasure, such as

    • A static variable is shared by all instances of a generic class, that is, generics cannot be used for static variables
    • A generic type parameter cannot be used in an exception-handling catch statement because exception handling is performed by the JVM at run time. Because of type erasure, the JVM has been unable to differentiate between two different types of exceptions originating from the same generic type.

6. Developing generic classes

Because of the type erase mechanism, the type parameter cannot be used (in a class) to create an object (such as T t=new T ()) or the type of a static variable.

/* generic class */  Public class Lhist<v>{}/* Create a generic class instance */lhist<integer>li=  New lhist<integer> (30);

7. Best Practices for generics

Common practice principles for using generics:

    • Avoid mixing generic classes with primitive types in your code, such as list<string> and list should not be used together.
    • Use the band wildcard character (? ), you need to clarify the concept of a set of types represented by wildcards.
    • You cannot instantiate a generic type variable and then use the reflected newinstance to create an instance, and you cannot create an array of generics.
    • Try not to ignore the warnings given by the compiler.

Java Collections and generics

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.