Java learning notes (generic)

Source: Internet
Author: User

Generic is an effective method for code-Level Reuse. Understanding the generic mechanism is conducive to better programming.

1) generic class
Package generictest;

Public class Mya {

Public Mya ()
{

}
Public string name;
Public String returnname ()
{
Return name + "hello ";
}
}
Package generictest;

Public class myb extends Mya implements myinterface {
Public myb ()
{

}

@ Override
Public String getxxxxname (){
// Todo auto-generated method stub
Return "from interface:" + this. Name;
}
}
Package generictest;

Public interface myinterface {
Public String getxxxxname ();
}
Package generictest;

Import java. util. Collections list;
Import java. util. List;
Import java. Lang. Reflect .*;
Import java. Lang .*;

Public class mygeneric <t extends Mya & myinterface>
{
Public writable list <t> objs = new writable list <t> ();
Public void addt (t obj)
{
Objs. Add (OBJ );
}
// If You Need to instantiate the parameter type, you need to pass the class type parameter.
Public void addt (string name, class <t> C) throws instantiationexception, illegalaccessexception
{
T OBJ = NULL;
// The conversion fails. The compilation is successful, but there will be errors.
// Class <t> theC = (class <t>) obj. getclass ();
// T theo2 = theC. newinstance ();
T theo2 = C. newinstance ();
Theo2.name = Name;
System. Out. println (theo2.getxxxxname ());
Addt (theo2 );
//
System. Out. println (theo2.returnname ());
}

}

2) generic method and Test

Package generictest; import Java. util. extends list; public class generictest {public static void main (string ARGs []) {mygeneric <myb> thegeneric = new mygeneric <myb> (); try {thegeneric. addt ("ABC1", myb. class); thegeneric. addt ("abc2", myb. class); thegeneric. addt ("abc3", myb. class); collections list <myb> theobjs = thegeneric. objs; For (myb theb: theobjs) {system. out. println (theb. name) ;}} catch (instantiationexception e) {// todo auto-generated catch blocke. printstacktrace ();} catch (illegalaccessexception e) {// todo auto-generated catch blocke. printstacktrace ();} // The following statement is incorrect because Mya does not comply with the constraint // mygeneric <Mya> thegeneric2 = new mygeneric <Mya> (); system. out. println ("") ;}// generic method public static <u extends Mya> U buildinstance (class <u> C) {try {return C. newinstance ();} catch (instantiationexception e) {// todo auto-generated catch blocke. printstacktrace ();} catch (illegalaccessexception e) {// todo auto-generated catch blocke. printstacktrace ();} return NULL ;}}

Summary:
1) Generic constraints are not mandatory. However, if a class constraint exists, only one class constraint can exist and must be placed at 1st bits;
2) If You Need to instantiate the generic type, you need to use the class <t> parameter to explicitly transfer it to the place where it needs to be instantiated, rather than directly instantiate it like the statement below: t thet = new T ();
At this point, C # is more convenient. As long as the generic type is added with the new () constraint, it can be instantiated to the generic type like the instantiated general class. t thet = new T ();
3) <u <t> invalid, that is, the generic type cannot be used as the generic type (allowed in C)
4) You cannot create a Generic Array (allowed in C)
Mygeneric <u> [] Thea = new mygeneric <u> [5]; // incorrect syntax.
5) generic types cannot be basic types, but must be class types (inherited from objects) (allowed in C)
Mygeneric <int> Thea = new mygeneric <int> (); // incorrect syntax.
6) The generic type cannot be determined by the instanceof test (allowed in C)
7) The generic type cannot be used for exception capture or exception throw. That is, if the generic type is a subclass of an exception-type exception, it cannot be captured or thrown. (allowed in C)
8) the generic type cannot appear in static methods (allowed in C)
Public class Singleton <t>
{
Public static t getsingleinstance () // Error
{
If (singleinstance = NULL) construct new instance of T
Return singleinstance;
}
Private Static t singleinstance; // Error
}

9) generic types are allowed to inherit, but must meet the constraints enhancement. That is, the constraints of subclass cannot be weaker than those of parent classes.
Public class mygeneric2 <t extends Mya & myinterface & runnable> extends mygeneric <t> {
} Is valid, but public class mygeneric2 <t extends Mya> extends mygeneric <t> {
} Is invalid.
10) If B is a subclass of A, but mygeneric2 <B> and mygeneric2 <A> do not have an inheritance relationship, they are two completely different types.
11) there is still a difference between using wildcards in generics and using general types. (This method is not in C # And is not necessary)

The generic mechanism of Java is different from that of C #. The generic mechanism of c # is more of a template, java generics use the underlying replacement method. In essence, the types in the underlying generic types are replaced with objects,

Just to help you with cast. at runtime, there is only one generic class instance, and C # Will instantiate the class instance according to different type parameters. The following test shows that:

Public class generictest1 <t> {public static int COUNT = 0; // No matter what type T is, the Count variable has only one copy, indicating that the generic class has only one class instance. public generictest1 () {count ++; system. out. println (this. count);} Public String t2string (t C) {count ++; system. out. println (this. count); Return C. getclass (). tostring ();}}

 

Public class generictest {public static void main (string ARGs []) {// defines the type parameter as an integer generic instance generictest1 <integer> theint = new generictest1 <integer> (); // output the theint type to generictest1 system. out. println (theint. getclass (); integer theintc = new INTEGER (1); system. out. println (theint. t2string (theintc); // it can be called as follows, indicating that the generic class is shared, not template. system. out. println (generictest1.count); generictest1 <generictest> thegenerictest = new generictest1 <generictest> (); // output the thegenerictest type to generictest1 system. out. println (thegenerictest. getclass (); generictest thetest = new generictest (); system. out. println (thegenerictest. t2string (thetest); // it can be called as follows, indicating that the generic class is shared, not template. system. out. println (generictest1.count );}}

From the test results, we can see that there are essentially differences between Java generics and C # generics. For Java, no matter what type parameters are, the class types of generic classes (in this example, generictest1) are the same, and all class members are shared. Understanding this is useful (instanceof) the root cause of no significance ). java aims to achieve backward compatibility. C # is often restructured. of course, this does not affect the quality of the two processing methods. The purpose is to make better use of these features.

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.