JAVA 41st-Basic Application of generics (1), java

Source: Internet
Author: User

JAVA 41st-Basic Application of generics (1), java


Generic is a security mechanism that emerged after JDK1.5. It simplifies the mechanism and improves security.

Advantages of generics

1. Transfer the ClassCastException during runtime to the compilation period.

2. Avoiding the trouble of forced conversion

<> When the referenced data type of an operation is unknown, you can import the referenced data type to be operated. <> actually, it is a parameter range used to receive specific referenced data types.

When writing a program, as long as you use a class or interface with <>, you must specify the specific reference data type of the transmitter.

Import java. util. arrayList; import java. util. iterator; public class Main {<span style = "white-space: pre"> </span> public static void main (String [] args) {<span style = "white-space: pre"> </span> ArrayList <String> al = new ArrayList <String> (); // specify that the ArrayList set only contains strings <span style = "white-space: pre"> </span> al. add ("abc"); <span style = "white-space: pre"> </span> al. add ("sd"); <span style = "white-space: pre"> </span> Iterator <String> it = al. iterator (); // After the iterator is clear, the <span style = "white-space: pre"> </span> while (it. hasNext () {<span style = "white-space: pre"> </span> String str = it. next (); <span style = "white-space: pre"> </span> System. out. println (str); <span style = "white-space: pre"> </span >}< span style = "white-space: pre" ></span> }}

Generic technology is used by compilers to ensure class security,During runtime, the generated class file does not contain generics and will be removed from the generics. This is the erasure of generics, the reason for erasure is to ensure compatibility with the running class loaders (if not erased, it means that the loaders also need to be upgraded, so they need to be erased)

With the extensive erasure, the generic compensation technology is introduced. At runtime, the conversion operation is performed by obtaining the element type, and no forced conversion is required.


Application of generics in a set

Import java. util. iterator; import java. util. treeSet; public class Man implements Comparable <Man> {private int age; private String name; public Man () {super (); // TODO Auto-generated constructor stub} public Man (String name, int age) {super (); this. age = age; this. name = name;} public int getAge () {return age;} public void setAge (int age) {this. age = age;} public String getName () {return name;} @ Overridepublic bo Olean equals (Object obj) {// TODO Auto-generated method stubreturn super. equals (obj);} public void setName (String name) {this. name = name ;}@ Overridepublic int compareTo (Man m) {// TODO Auto-generated method stubint t = this. name. compareTo (m. name); return t = 0? T: this. age-m.age; }} public class Main {public static void main (String [] args) {TreeSet <Man> ts = new TreeSet <Man> (); // You can construct a comparator ts. add (new Man ("a", 1); ts. add (new Man ("a", 4); ts. add (new Man ("B", 5); ts. add (new Man ("d", 2); ts. add (new Man ("c", 7); Iterator <Man> it = ts. iterator (); while (it. hasNext () {Man m = it. next (); System. out. println (m. getName () + "," + m. getAge ());}}}


Custom generic class

// Define a Tool class to manipulate all objects/* public class Tool {private Object obj; // use Objectpublic Object getObj () {return obj;} to improve scalability ;} public void setObj (Object obj) {this. obj = obj ;}} * // custom generic class after JDK1.5. When the referenced data type of operations in the class is not determined, use generics to represent public class Tool <E> {private E e; public E getObj () {return e;} public void setObject (E obj) {this. e = obj ;}} public class Student extends Man {// The Man class has the public Student () {super (); // TODO Auto-generated constructor stub} public Student (String name, int age) {super (name, age ); // TODO Auto-generated constructor stub} public class Worker extends Man {public Worker () {super (); // TODO Auto-generated constructor stub} public Worker (String name, int age) {super (name, age); // TODO Auto-generated constructor stub} public class Main {public static void main (String [] args) {// before JDK1.5/* Tool to = new Tool ();. setObj (new Worker (); // once a Worker is accidentally uploaded, it passes during compilation, and the exception ClassCastExceptionStudent student = (Student). getObj (); // but strong conversion * // Tool <Student> to = new Tool <Student> ();. setObject (new Student (); // once a Worker is accidentally transferred, the compilation will fail, and the benefits of generics will be reflected, check mentioned Student student =. getObj (); System. out. println (student. getClass ());}}


Generic method: Define generic in a method

Class Tool <E> {private E e; public E getObj () {return e;} public void setObject (E obj) {this. e = obj;} public <O> void show (O str) {// define the generic type on the method, and print the type of System. out. println ("Tool. show () "+ str);} public <O> void printf (O str) {System. out. println ("Tool. printf () "+ str);} // public static void mhtodd (E e) {} if the generic type is defined on the static struct class, the compilation fails, static objects do not need to be modified. Only public static <F> void mthod (F str) {System. out. println ("Tool. mthod () "+ str) ;}} public class Main {public static void main (String [] args) {Tool <String> to = new Tool <String> (); to. show ("asd");. show (new Integer (5);. printf ("pri"); // while printf does not support Tool except for string. mthod ("Haha"); Tool. mthod ('F ');}}


Disadvantages of generics

In the show method above, if String is input, str cannot be used. length () method. Because the generic type is uncertain, the method of a class cannot be determined. Only some methods of some objects can be used.



A few lines of code are not familiar with basic Java generic applications. Let's take a look.

This is a newly added function of java1.5.
1. variable parameters. It is applicable to situations where the number of parameters is uncertain and the type is determined. java treats variable parameters as arrays. Note: The variable parameter must be in the last one. There can be only one variable parameter. Java code

Public class TestVariable {
Private static int count = 0;
Public static void main (String args []) {
Get ("1", new Object [] {"1", "2", "3 "});

}
Private static void get (String string, Object... object ){
For (Object o: object ){
System. out. println (o );
}

}

}
Result:
1
2
3
2. This is called foreach,
For (T t: param ){
System. out. print (t + ",");
}
Equivalent:
For (int I = 0; I <param. length; I ++)
{
T t = param [I];
System. out. print (t + ",");

}

Java, generic learning

In fact, generics are a standard for development. When more development is done, you can understand that they are actually very useful. For example, you can set each record of the query result list, each attribute is encapsulated in A class, such as: public class Demo {private String A; private String B; private String C (get (), set ())}, you can use the generic type in the query results. List <Demo> list = new ArrayList <Demo> (); after the Declaration, you can easily obtain the specific attribute values of a record, for example, you want the value of the third record: list. get (2 ). getA. Of course, if you do not add a generic type, you can perform a forced conversion of type ..... It is not difficult to drill in a generic model, and it does not need to be drilled in. It may be a bit difficult to understand, but it takes a long time, you will understand why generics are added. In addition, when you go to a formal software company, development specifications will require you to use generics, in this way, when others look at your code, they will also know what attributes are in the list. Well, I don't think I can express myself very well, ask again if you have any questions.

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.