Object-oriented, Java generic article

Source: Internet
Author: User
Tags array definition

I. Basics of getting Started with Java generics

1. Generic history: Any type of object can be stored in the collection, but when taken out, if you want to use the specific method of the concrete object, you need to make a downward transformation, if the stored object type is inconsistent, there will be a classcastexception exception during the transformation process. This gives the program an unsafe result.
After jdk1.5, there is a solution-generic technology: When storing elements, it is not allowed to store different types of elements. The compilation failed when it was stored. So it is necessary to define the specific element type on the container when storing the element, which is actually the same as the array definition.

2, Advantages: 1) The operation period of the classcastexception abnormal transfer to the compilation period, to check, and to compile the failure to reflect. This helps programmers solve problems early.
2) Avoid the trouble of downward transformation (strong turn).

3. Under what circumstances is the generic type used?

Whenever a class or interface is used, the class or interface is <> when the API text is described, and you need to define generics when you use it.
In fact, generics are nothing more than a formal parameter defined by <>, specifically for receiving specific reference types. When used, be sure to pass the corresponding actual parameter type.
The use of generics in collections is particularly common.


Second, Java generics use

Examples of motivations using generics (in the case of collections):

Class MySet: (self-written myset, Java generics implemented)

public class Myset<e> {private object[] objs=new object[0];p ublic boolean add (E obj) {if (contains (obj)) {return false;} Object tempobjs[] = new object[objs.length+1]; System.arraycopy (OBJS, 0, TEMPOBJS, 0, objs.length); Tempobjs[objs.length] = Obj;objs = Tempobjs;return true;} Public Boolean contains (E obj) {for (Object o:objs) {if (o.equals (obj)) {return true;}} return false;} Public object[] GetAll () {return OBJS;} public int size () {return objs.length;}}

Test class:

Import Java.util.arraylist;import Java.util.iterator;public class GenericDemo2 {public static void main (string[] args) { myset<string> set = new Myset<string> ()//set.add ("ABCD");//set.add (8);//Compilation Error//myset<integer> set = new Myset<integer> ();//set.add ("ABCD");//Compile Error//set.add (8);}}

Note: When a variable is declared as generic, it can only be called by instance variables and methods, not by static variables and methods. The reason is simple, parameterized generics are some instances. Static members are shared by instances of classes and parameterized classes, so static members should not have type parameters associated with them.

Third, Java generic class

1, Concept: When a class to manipulate the reference data type is undefined, you can define a formal parameter of the type. When used, this class is used by the user to determine the specific object type to manipulate by passing the type parameter form. This means that when defining this class, you need to define the formal parameters on the class to receive the specific type arguments. This is the definition of generics on a class, that is, a generic class.

2. When do you use generic classes?

A generic class can be defined as long as the reference data type of the operation in the class is undefined. Having a generic class eliminates the hassle of having a strong transition and type conversion exception.

code example:

/* * Generic class Demo */public class GenericDemo2 {public static void main (string[] args) {myvessel<worker> u = new MYVESSEL&L T Worker> ();//u.setobject (new Student ());//No, the worker is stored in U, the argument can only be worker type U.setobject (new Worker ()); Worker w = u.getobject (); System.out.println (w); Myvessel<student> v = new myvessel<student> ();//v.setobject (new Worker ());//No, argument can only be Student type}}class myvessel<e>{//From the syntax of "E" to take into other names such as "QQ" is also possible, but not standard. Private E obj;public void SetObject (E obj) {this.obj = obj;} Public E GetObject () {return obj;}} Class student{string profession;} Class Worker{string Company;}

Iv. Java Generic methods

1. Definition of generic method (generic bundle with Class)

The type of the method to manipulate is indeterminate, but is consistent with the type specified by the object that called the method.

2. Definition of generic method (generic type independent of Class)

The type of the method to manipulate is indeterminate and is not necessarily the same as the type specified by the object that called the method.

3. Definition of generic method (generic for static methods)

A static method cannot access a generic defined on a class because it does not have an object. If a static method requires generics, the generic type can only be defined on the method.

code example:

The class demo<w>{//method is consistent with generics and classes, or is dependent on the generic public void Show (W) {System.out.println ("Show:" +w.tostring ()) of classes;} Non-generic, unsafe. Because the caller can strongly convert the return value of the method to another type, a strong exception occurs with the public object Myprint0 (object a) {System.out.println ("Myprint:" +a); return A;} Methods are generic, but the requirements and generics of the class are independent of each other. The return type and method can be qualified with the same arguments, are more secure, and do not have to be strongly turned. Public <A> a Myprint (a a) {System.out.println ("Myprint:" +a); return A;} Static methods with generics, generics must be independent of the class, because it has no objects. public static <A> a Myprint2 (a a) {System.out.println ("Myprint:" +a); return A;}}


V. Java generic interface

This is not a good explanation for the direct code example:

Interface Inter<v>{public Abstract v Show (v v);} The definition of a class that implements a generic interface. The parameter types in the method are consistent with the type specified when the class declaration implements the interface, and have been determined to be string!-----This example assumes that we are writing this class to know that it is a class Interimpl implements dedicated to handling string data inter< string>{@Overridepublic string Show (string s) {System.out.println (s); return s;}} The definition of a class that implements a generic interface. The type of the parameter in the method and the class declaration implement the interface when the specified types are consistent, but not sure!-----This example assumes that we do not know what type of data the class is dealing with when we write this class, but one thing is certain: what type (generic argument) is specified when declaring the class object, and the Show method processes the type class Interimpl2<c> implements inter<c>{@Overridepublic C show (c s) {System.out.println (s); return s;}}


Vi. Java Generics advanced

(PS: High-level applications on Java generics, minimum requirements: Although you may not be able to write such a similar definition, But you have to use or call (other programmers or APIs have already used this technology to write classes or methods), so here only to do the simplest introduction, interested bloggers can go deep learning, Bo Master Ability Limited, hey. )

1. Generic wildcard characters:?

When the types in the different containers of the operation are not deterministic, and the elements are used to inherit from the object class, the generic is represented by a wildcard character. (Metaphor for understanding: polymorphic applications in generics)

2, the generic type of qualification:

The type of operation is limited to one range. For example: Define a function to manipulate only the person type or the subtype of person. This can be used:
? Extends e: Receives subtype of e type or E. This is the upper limit.
? Super E: Receives the type E or the parent of E. This is the lower limit.

Under normal circumstances:
Use the upper bound whenever you add an element to a container. Extends E
The lower bound is used whenever the element is removed from the container. Super E
Advanced only so much, Bo friends can go to the API to see this situation, for example: Collection

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Object-oriented, Java generic 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.