Java------Generics "from basics to strengthening"

Source: Internet
Author: User
Tags addall array definition

Generic type

Basic article One, why to generics 1, reason

First look at a set of examples (as for the collection, the previous explanation, set a detailed link, do not know how to go to see that article)

import java.util.arraylist;import java.util.collection;import Java.util.HashSet; Import Java.util.iterator;import Cn.hncu.bean.person;public class Collectiondemo {public static void main (string[] args {Collection col = new ArrayList ();//increment Addcol.add (New person ("qwe"));//From jdk1.5, you can automatically package Col.add (new person ("DF") ), Col.add (New person ("AF")), Col.add (New person ("FGR")), Col.add (new person (+, "et")), Col.add (new person (27, " Ghj "));//Add duplicate elements, for list is OK, and for set is not added. Delete Remove removes the element itself//col.remove (3);//col.remove (2);//Change//col.remove (1); Col.add (4); Unreasonable, because the position changed//object objs[] = Col.toarray ();//col.clear ();//for (int i=0;i<objs.length;i++) {//if (Objs[i].equals ( 1) {//objs[i]=4;//}//col.add (objs[i]);//}iterator<object> it = Col.iterator (); while (It.hasnext ()) {Object obj = It.next (), if (obj instanceof person) {System.out.println ("Object:" +obj); else if (obj instanceof Integer) {System.out.println ("int:" +obj);} Else{system.out.println ("Other:" +obj);}}} 

This program is a simple set, first input and output. I see no problem, even if put in MyEclipse run, the result is right. But you will find that there are a lot of yellow exclamation points in the MyEclipse, which indicates that the program has a warning, that is, there is an unsafe factor.

The reason for these warnings is that the collection can hold a variety of different kinds of elements, but when it is taken out, it is not certain what type it is when it is placed.

Written explanation: Any type of object can be stored in a collection, but when taken out, if you want to use a specific method of a particular object, you need to make a downward transition, and if the stored object type is inconsistent, a classcastexception exception will occur during the transition. 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. (array definition: int[], double[], class name [],string[], etc.

Wait, look at the writing should be able to understand the twos, the front is clear the type of the array)

To remove the yellow exclamation mark above, just change these two sentences:

collection<person> col = new Arraylist<person> ();iterator<person> it = Col.iterator ();

2. Benefits

1) The ClassCastException anomaly of the running period is transferred to the compile time, which is checked and reflected by the compilation failure. This helps programmers solve problems early.

2) Avoid the trouble of downward transformation (strong turn).

Cases:

Import Java.util.arraylist;import Java.util.iterator;public class GenericDemo1 {public static void main (string[] args) { Demo1 ();d Emo2 ();} private static void Demo1 () {ArrayList alist = new ArrayList (); Alist.add ("ABCD"); Alist.add ("Abcewew"); Alist.add ("a333d "); Alist.add (8);//compile Yes, but there is an error in the runtime. This is not safe, in terms of software development, very unfavorable. Iterator it = Alist.iterator (); while (It.hasnext ()) {String str = (string) it.next (); str = Str.touppercase (); System.out.println (Str.length ());}} private static void Demo2 () {arraylist<string> alist = new arraylist<string> (); Alist.add ("ABCD"); Alist.add ("Abcewew"); Alist.add ("a333d");//alist.add (8);//Add generics, the sentence will be directly error. Benefits of Generics (1) iterator<string> it = Alist.iterator (); while (It.hasnext ()) {String str = it.next ();//Plus generics, no type-strong turn is required. Benefits of Generics (2) str = Str.touppercase (); System.out.println (Str.length ());}}}
Call Demo1 (), put the time with two different types of elements, compile without error, when the output, because no generics, so to strong turn, the problem appears in this, the int of the 8 strong to the string will be error, that is, run-time error.

Call Demo1 (), because the use of a generic in advance, that is, the set of what type of data to put, so after the completion of the Add (8), will be directly error. And the back of the output, there is no need to turn strong.

In a nutshell, Java writes a container that can manipulate many different types of elements at the same time, that is, a collection, but when it is used, it finds that there is an unsafe factor, so when it is used, it also prescribes the only one, that is, the generic type. (like an array )

Second, the principle of the use of generics 1, when to write generics

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 generic type in the collection should be

Very much.

2, the generic type erase

Generic technology is used for the compilation period of technology, the compiler will follow the specified type of <> to check the elements, check the mismatch, the compilation failed, matching, compiled through, after the production of the class file is not generic, this becomes a generic erase.

3, the compensation of the generic type

At run time, you can obtain its specific type based on the specific element object and use that type to automatically convert the elements. ( that is, when you take it out, you don't have to use a strong turn. )

Iii. use of generics 1, examples of motivations for using generics (in the case of collections):

Restricts the type of elements stored in the collection to prevent late errors. If you qualify a collection to hold only the person class object (because the element is later removed as a person object), the other types of objects will be compiled with an error. equivalent to a

Classes are generalized into many different types (materialized, qualified) classes.

The code used by generics is as follows:

list<person> persons = new arraylist<person>; map<string,string> m = new hashmap<string,string>;

2, the meaning of the generic type

When defining a generic class or declaring a variable of a generic class, use angle brackets to specify a form type argument, called a type parameter, and the actual type passed at invocation becomes a type argument. The relationship between type participation type arguments is similar to the relationship between the formal method parameter and the actual method parameter, except that the type parameter represents the type, not

is the value to represent.

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.

Iv. generic Class (Custom) 1, defined as a generic class case

When a class is unsure of the reference data type to manipulate, you can define a parameter for that 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.

Cases:

/* * 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;}

2. Benefits of generic classes

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.

3. Definition of generic method

1) 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) 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) 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.

Cases:

/* * Generic method Demo */public class GenericDemo3 {public static void main (string[] args) {tool<string> t1 = new Tool<strin G> (); T1.show ("abc");//t1.show (new Integer (6));//not, because the T1 limit can only handle string data tool<integer> t2 = new tool< Integer> ();//t2.show ("abc");//not, because the T2 limit can only handle integer data t2.show (New Integer (6)); String s = t1.myprint ("AAA"); System.out.println (s); int i = t1.myprint (New integer (6)),//string s2 = t1.myprint (New integer (6));//No, because generics are defined on methods, And the return type and the method's argument type are consistent System.out.println (i);}} The class tool<w>{//method is consistent with generics and classes, or the generic method that relies on classes 1public void Show (W) {System.out.println ("Show:" +w.tostring ());} 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. Method 2public <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. Method 3public Static <A> a Myprint2 (a a) {System.out.println ("Myprint:" +a); return A;}

Five, generic interface

public class GenericDemo4 {public static void main (string[] args) {String str = new Interimpl (). Show ("abc"); System.out.println ("main:" +str);//integer i = new interimpl2<integer> (). Show (+);interimpl2<integer> mm = new interimpl2<integer> ();//mm.show ("AAA");//The previous sentence has a generic type, so a compilation error is reported here int i = mm.show (80); System.out.println (i);}} 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;}}



Strengthen the one-and-generic wildcard character:?

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)

Import Java.util.arraylist;import Java.util.iterator;public class Genericadvdemo1_1 {public static void main (string[] args) {arraylist<string> a1 = new arraylist<string> () A1.add ("ABC1"); A1.add ("ABC2"); A1.add ("ABC3"); arraylist<integer> A2 = new arraylist<integer> () A2.add, A2.add (6); A2.add (8);//printcoll (A1);// This method can only output a1//printcoll2 (A2);//<span style= "font-family:arial, Helvetica, Sans-serif;" > This method can only output a2</span>printcoll3 (A1),//This method can output A1 can also output A2, this is the use of generic wildcard printColl3 (A2);} /* The solution is right from the idea, but it doesn't work in a grammatical way. Because this is a run-time polymorphism, and our generics are in the compile-time public static void Printcoll (Arraylist<object> a) {iterator<object> it = A.iterator () ; while (It.hasnext ()) {Object str = it.next (); System.out.println (str);}} */public static void Printcoll (Arraylist<string> a) {iterator<string> it = A.iterator (); while (It.hasnext () ) {String str = it.next (); System.out.println (str);}} public static void PrintColl2 (Arraylist<integer> a) {iterator<integer> it = A.iterator ();(It.hasnext ()) {Integer str = it.next (); System.out.println (str);}} public static void PrintColl3 (Arraylist<?> a) {iterator<?> it = A.iterator (), while (It.hasnext ()) {Object str = It.next (); System.out.println (str); Element can only invoke methods inherited from the object class}}}


Ii. limitation of generic type

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.

Import Java.util.arraylist;import Java.util.iterator;public class GenericAdvDemo3 {public static void main (string[] args) {arraylist<person> a1 = new arraylist<person> (), A1.add (New person ("Jack1")), A1.add (New person (" Jack3 "," A1.add "(" Jack2 ", 22)); arraylist<integer> A2 = new arraylist<integer> (); A2.add (+); A2.add (6); A2.add (8); arraylist<student> a3 = new arraylist<student> () A3.add (New Student ("AA"); A3.add (New Student ("BB", 20 ); A3.add (New Student ("CC"));p Rintcoll (A1);//printcoll (A2);p rintcoll (A3);} /* Write yourself a generic method with an upper limit of */public static void Printcoll (ARRAYLIST<? extends person> a) {iterator<? extends person> it = A. Iterator (); while (It.hasnext ()) {person P = it.next (); System.out.println (P.getname ()); Element can only invoke methods inherited from the Person class}}}


? Super E: Receives the type E or the parent of E. This is the lower limit.

API view: The generics in the AddAll () method in collection is the use of a cap. The construction method of the TreeSet class uses the upper and lower bounds respectively.

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

Import Java.util.arraylist;import java.util.collection;import java.util.comparator;import java.util.Iterator; Import Java.util.treeset;public class GenericAdvDemo2 {public static void main (string[] args) {//demo upper limit, application: Put elements in Set// Extendsedemo ();//demo lower limit, application: Take element from collection Superedemo ();} private static void Extendsedemo () {collection<person> coll = new arraylist<person> (); Coll.add (New Person (" Jack, Coll.add ("Tom", 124), Coll.add ("Rose", 25)); collection<student> coll2 = new arraylist<student> () Coll2.add (New Student ("Jack2", 223)); Coll2.add (new Student ("Tom2", 224)); Coll2.add (New Student ("Rose2", 225)); treeset<person> ts = new Treeset<person> (coll), Ts.add (New Student ("AAA"), Ts.addall (COLL2);//Upper limit: The element type (generics) in Coll2 must be a subclass of person or person iterator<person> it = ts.iterator (), while (It.hasnext ()) {person P = it.next () ; System.out.println (P.tostring ());} treeset<student> ts2 = new Treeset<student> (coll2);//iterator<student> it2 = tS2.iterator ();//while (It2.hasnext ()) {//student p = it2.next ();//system.out.println (p.tostring ());//}}private static void Superedemo () {//treeset<student> ts = new treeset<student> (new CompByName1 ()); treeset<student> ts = new treeset<student> (new Compbyname ()), Ts.add (New Student ("Lisi1"), Ts.add (new Student ("Lisi3"); Ts.add (New Student ("Lisi2");iterator<student> it = Ts.iterator (); while (It.hasnext () ) {Student p = it.next (); System.out.println (P.tostring ());} treeset<worker> ts2 = new treeset<worker> (new CompByName2 ()); treeset<worker> ts2 = new treeset<worker> (new Compbyname ()), Ts2.add (New Worker ("lisi21"), Ts2.add (new) Worker ("lisi23"), Ts2.add (New Worker ("lisi22"));iterator<worker> it2 = Ts2.iterator (); while ( It2.hasnext ()) {Worker p = it2.next (); System.out.println (P.tostring ());}}} @SuppressWarnings ("rawtypes") class person implements comparable{string Name;int age;public person (String name, Int. age) {ThiS.name = Name;this.age = age;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} public int getage () {return age;} public void Setage (int.) {this.age = age;} @Overridepublic int compareTo (Object o) {person p = (person) O;return this.age-p.age;} @Overridepublic String toString () {return ' person [name= + name + ', age= ' + Age + '] ";}} Class Student extends Person{string profession;public Student (String name, int age) {Super (name, age);}} Class CompByName1 implements comparator<student>{@Overridepublic int compare (Student s1, Student S2) {return S1.getname (). CompareTo (S2.getname ());}} Class worker extends person{string company;public worker (String name, int age) {Super (name, age);}} Class CompByName2 implements comparator<worker>{@Overridepublic int compare (worker S1, worker S2) {return S1.getname (). CompareTo (S2.getname ());}} Take advantage of the "comparator&lt" in generics; Super E> Comparator "is the lower limit feature, make a general comparator (compare all person and subclass object 0class Compbyname implements Comparator<person>{@Overridepublic int Compare (person S1, person S2) {return s1.getname (). CompareTo (S2.getname ());}} 















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

Java------Generics "from basics to strengthening"

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.