Java Paradigm-Basics

Source: Internet
Author: User
Tags comparable

Java Paradigm-Basics

The concept of a generic type

1, the realization of the parameterization of the type

2. For writing code that can be applied to multiple types, the code you write can be applied to many many types.

3, fan-type container, fan-type interface, model method are the classic usage.

Ii. Generics and polymorphism

1, polymorphism is a generalization mechanism. In the use of type descriptions, the use of polymorphism does provide some flexibility. However, polymorphism is restricted: only the base class or its subclasses can be accepted (in the single inheritance system, so that the program is limited too much). Also, when you actually write code, you can only use a base class or interface that already exists. At the same time, once the interface is indicated, the program requires that your code must use a specific interface (method).

2. Generics: Enables us to write code that is more flexible and more generic than polymorphic, which enables code to be applied to "some kind of non-specific type" rather than to a specific interface or class.

3. Code written using a generic mechanism is more secure and readable than those that use the object variable in a cluttered manner, and then enforce the type conversion.

4. Another advantage of generics: the ability to detect errors at compile time, not at run time. For example:

JDK1.5 before: public interface comparable{public int Comparato (Object 0)}

Compile pass, run error

Comparalbe C = new Date (); Date implements the Comparalbe

C.compareto ("Red");

Jdk1.5:public interface Comparable<t>{public int Comparato (T 0)}

Compilation error because the argument passed to CompareTo () must be of type date

comparalbe<date> C = new Date (); Date implements the Comparalbe

C.compareto ("Red");

Iii. limitations of generics

1. The base type cannot be used as a type parameter. For example:

Comparalbe<int> is wrong and should be comparalbe<integer>.

2. You cannot create an instance with a generic type. For example:

E object = new E ();

3. You cannot create an array with a generic type. For example:

e[] elements = new E[10];

(You can create an object array and then convert its type to e[] to circumvent this limitation)

(e[] elements = (e[]) new OBJECT[10];)

(with compile warning)

4. You are not allowed to create generic arrays using the Paradigm class. For example:

arraylist<string>[] List = new arraylist<string>[10];

(Can use: arraylist<string>[] list = (arraylist<string>[]) New ArrayList [ten];)

(with compile warning)

5. In a static environment (static domain, static method, static block), the parameter of the class is not allowed to be a generic type.

public class test<e>{//class parameter is generic

private static E o; Static domain

public static void M (E 0) {}//static method

static{}//Static block

}

6, the exception class cannot be generic. For example:

public class Myexception<t> extends exception{

}

Iv. generic Method (parametric method)

1, generic methods can be in a generic class, also in a non-generic class. That is, whether you have a generic method or not is not related to whether it is a generic class.

2. The generic method enables the method to change independently of the class. If you use generic methods instead of generics for the entire class, you should use only generic methods.

3. Generic method definition: You only need to place the generic parameter list before the return type. For example:

Private <T> void m (T t) {}

public static <T> T m () {return t;}//t t

4. Generic method invocation: The same as a call to a normal method.

V. Generic Interfaces and Classes

1. Definition of generic interface and class: Enclose the type parameter with angle brackets, and place it behind the interface (class name). For example:

public class holder<t>{}

public Interface inter<t>{}

2. READ: Class with T type parameter.

3. Classic usage of generic interfaces and classes: generic containers.

Vi. boundary (generic parameter type Qualified): <t extends Boundingtypelist>

1. T: Sub-class or sub-interface boundingtypelist for the boundary list

2, Boundingtypelist: The limit list can have at most one class, or multiple interfaces, and the class must be placed first in the bounds list. The bounds list uses & joins, for example,

Boundingtypelist:class & Interfacea & INTERFACEB

Note: Where class is called the first boundary, Interfacea is the second boundary, and so on. If there is no bounds list, object is the first boundary.

3, generic type-qualified, also known as the boundary of a generic type. It allows us to set restrictions on the type of parameters used for generics, which specifies the types that generics can apply (these generic types should meet the constraints). Another more important effect is that the method can be called according to its own boundary type, whereas the method called by the unbounded generic parameter is just those that can be called with an object (in the next section).

Vii. Generic translation: Erase

1. The Mystery of erasing

1) arraylist<string> and arraylist<integer>

Main ()

Class C1 = new arraylist<string> (). GetClass ();

Class C2 = new arraylist<integer> (). GetClass ();

SYSTEM.OUT.PRINTLN (C1 = = C2);

Output

Ture

Obviously, we all think that arraylist<string> and arraylist<integer> are different types. However, the results of the program run show that:arraylist<string> and arraylist<integer> are the same type. This is because: within the generic code, you cannot get any information about the type of the generic parameter (which is one of the reasons why the use of generics is limited, for example, you cannot create a generic array).

2) The problem with erasing: When using generics, any specific type of information is erased, and we only know that when using a native object (object) (if the boundary is not used), the only method we can invoke is only those methods that can be called with an object.

Class hasf{public void F () {System.out.println ("hasf");}}

Class temp<t>{

T obj;

Public Temp (T aobj) {obj = aobj;}

public void Meth () {obj.f ();}//compile Error

}

Main ()

New Temp

This is because the compiler is unable to map meth () to the fact that the requirement of f () on obj is mapped to hasf owning F (). To solve this problem, we need to go to the generic boundary (the generic type parameter is erased to its first boundary, and no boundary is erased to the native object).

Class Temp<t extends hasf>{//boundary hasf, all hasf exposed methods can be called

T obj;

Public Temp (T aobj) {obj = aobj;}

public void Meth () {obj.f ();}//

}

2. Generic type

Whenever a generic type is defined, the corresponding original type (raw types) is automatically supplied. The name of the original type is the name of the generic type that deleted the type parameter. The type parameter T is erased (erased) and replaced with the first boundary (an unqualified type variable with object). For example:

Generic//primitive type (type parameter erase)

public class pair<t>{public class pair{

Private T Frist; Private Object Frist;

Private T second; Private Object second;

Public T getfrist () {Retrun frist;} Public Object getfrist () {Retrun frist;}

public void Setsecond (T asecond) {...} public void

Setsecond (Object asecond) {...}

}                                   }

3. Generic method

1) Type erase is also performed, the type parameter t of the generic method is erased (erased), and the first side

Bounds (variables with unqualified types are replaced with object). For example:

Public <t extends comparable> T m () {...}//generic method

Public comparable m () {...}//Erase method

2) problems caused by generic method erasure: conflicts with polymorphism

Before erasing

Class DateInterval extends pair<date>{

public void Setsecond (Date asecond) {...}

}

After erasing

Class DateInterval extends pair{

public void Setsecond (Date asecond) {...}

}

Meanwhile, DateInterval inherits the method from the pair

public void Setsecond (Object asecond) {...}

Obviously, DateInterval has two Setsecond () methods, if the following statement is executed

DateInterval interval = new DateInterval ();

Pair<date> pair = interval;

Pair.setsecond (adate);

The call to Setsecond () is polymorphic, the pair references the Dateinterva object, and we want to invoke the

DateInterval. Setsecond (). The problem is that type erasure conflicts with polymorphism. Workaround:

The compiler generates a bridge method in DateInterval.

public void Setsecond (Object asecond) {Setsecond ((Date) second)}

3) Generic expression: The return type is erased, the compiler inserts a forced type conversion

Pair<employee> buddies = ...;

Employee buddy = Buddies.getfrist ();

The call to Getfrist () is a call to the original method, Getfrist (), and then the returned object is forced//swapped for the employee

Java Paradigm-Basics

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.