Java generics learning ——————
Benefits of generics
1. At compile time, check the type of the added element to improve security
2. Reduce the number of type conversion and improve efficiency
Examples are as follows: do not use the generic Dog-> Add ->Object-> Fetch ->Dog// Putting into ArrayList will go to Object, fetching also needs to go to Dog
import java.util.ArrayList;
public class Dog {
private String name;
private int age;
public Dog(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 age) {
this.age = age; }}class Cat{
private String name;
private int age;
public Cat(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 age) {
this.age = age; }}class Generic{
public static void main(String[] args) {
ArrayList list= new ArrayList();
list.add(new Dog("Prosperous wealth.".12));
list.add(new Dog("Get rich".1));
list.add(new Dog("Yellow".13));
// Add a cat. There is no error when compiling, but there is an error when running
list.add(new Cat(Lucky Cat.23));
// Enhance the for loop
for(Object o:list){
// Downward transition Object-- Dog
Dog dog=(Dog)o;
System.out.println(dog.getName()+"-"+dog.getAge()); }}}Copy the code
Generics are used
Dog->Dog->Dog is put in and taken out without casting
As an example, we modify the Genreic class code
、、、、、、、 the Cat and Dog classes remain the samepublic class Genreic {
public static void main(String[] args) {
ArrayList<Dog> list=new ArrayList<Dog>();
list.add(new Dog("Fortune Dog".23));
list.add(new Dog("Dog".25));
// Generic constraint, compiler detection, failure to meet the requirements will be reported
// list.add(new Cat(" Cat ",23));
// If it is convenient, you can simply fetch the Dog type instead of the Object type
for (Dog o:list){
System.out.println(o.getName()+"-"+o.getAge()); }}}Copy the code
Generic introduction
Generics, also known as parameterized types (generics can be understood as a data type that can represent data types), is a new feature in jdk5.0 that addresses the problem of data type safety
Note 1 that the data types pointed to by generics are required to be reference data types, not base data types
ArrayList<Integer> list1=new ArrayList<Integer>();
// ArrayList
list2=new ArrayList
();
Copy the code
Note 2: After assigning a specific type to a generic type, you can assign it or its subclass type
public class Test {
pig<A>pig=new pig<A>(new A());
// After specifying a specific type for a generic type, you can pass it or its subclass type to the type
pig<A>pig2=new pig<A>(new B());
}
class A{};
class B extends A{};
class pig<E>{
E e;
public pig(E e) {
this.e = e; }}Copy the code
Note 3: If you do not specify a data type for a generic, the compiler defaults to Object
// The default generic is Object, which is equivalent
ArrayList list=new ArrayList();
ArrayList<Object>list2=new ArrayList<>();
Copy the code
Practical subject
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
class Eployee {
private String name;
private int sal;
private Mydata birthdy;
public Eployee(a) {}public Eployee(String name, int sal, Mydata birthdy) {
this.name = name;
this.sal = sal;
this.birthdy = birthdy;
}
public String getName(a) {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSal(a) {
return sal;
}
public void setSal(int sal) {
this.sal = sal;
}
public Mydata getBirthdy(a) {
return birthdy;
}
public void setBirthdy(Mydata birthdy) {
this.birthdy = birthdy;
}
@Override
public String toString(a) {
return "\nEployee{" +
"name='" + name + '\' ' +
", sal=" + sal +
", birthdy=" + birthdy +
'} '; }}class Mydata implements Comparable<Mydata>{
private int month;
private int year;
private int day;
public Mydata(a) {}public Mydata(int year, int month, int day) {
this.month = month;
this.year = year;
this.day = day;
}
public int getMonth(a) {
return month;
}
public void setMonth(int month) {
this.month = month;
}
public int getYear(a) {
return year;
}
public void setYear(int year) {
this.year = year;
}
public int getDay(a) {
return day;
}
public void setDay(int day) {
this.day = day;
}
@Override
public String toString(a) {
return "Mydata{" +
"month=" + month +
", year=" + year +
", day=" + day +
'} ';
}
@Override
public int compareTo(Mydata o) {
int yearminth=year- o.getYear();
if(yearminth! =0) {return yearminth;
}
//比较minth
int monthminth=month-o.getMonth();
if(monthminth! =0) {
return monthminth;
}
returnday-o.getDay(); }}class Test{
public static void main(String[] args) {
ArrayList<Eployee>list=new ArrayList<>();
list.add(new Eployee("tom".30000.new Mydata(2000.11.27))); list.add(new Eployee("jact".12000.new Mydata(2001.12.12))); list.add(new Eployee("tom".60000.new Mydata(2000.10.27))); System.out.println("eplyees"+list);
System.out.println("----------------- sort after ------------------");
list.sort(new Comparator<Eployee>() {
@Override
public int compare(Eployee o1, Eployee o2) {
// Validates the argument passed first
if(! (o1instanceof Eployee && o2 instanceof Eployee)) {
System.out.println("Type mismatch");
return 0;
}
// Compare the names if the types are the same
int i = o1.getName().compareTo(o2.getName());
if(i ! =0) {
return i;
}
// Compare birthdays
returno1.getBirthdy().compareTo(o2.getBirthdy()); }}); System.out.println(list); }}Copy the code
Custom generics
The basic grammar
classThe name of the class"T.R..>{// There can be multipleMembers of the... }Copy the code
Ordinary members can use generics
Copy the code
Arrays that use generics cannot be initialized
class Targer<T.R.M>{
String name;
T t;
R r;
M m;
// Because the array in new cannot determine the R data type, can not know how much space to open
// R[]rs =new R[8];
// But it can be defined
R[]rs2;
}
Copy the code
Class generics cannot be used in static methods
class Targer<T.R.M>{
String name;
T t;
R r;
M m;
// Because static is class dependent, the object is not created when the class is loaded
// If static methods and properties use generics, the JVM cannot complete initialization
static T t;
public Static void m1 (T t){}}Copy the code
Custom generic interfaces
The basic grammar
Static members cannot use generics in the interface either
The type of a generic interface that can be inherited or implemented
Interface Interface name <T,R.. > {}Copy the code
package com.taoge.con;
interface Test2<U.R> {
int n=10;
// Properties are static properties in the interface
// U name; error
// Interface generics can also be used for normal methods
R get(U u );
void hi(U u,R r);
// In JDK8, you can use default methods in the interface, or you can use generics
default R meth(U u){
return null; }}// Implement the type of the interface when inheriting it
interface Test3 extends Test2<String.Double>{}
// When we implement Test3, we specify U as String and R as Double in Test2
// Automatically replace methods when implemented
class person implements Test3{
@Override
public Double get(String s) {
return null;
}
@Override
public void hi(String s, Double aDouble) {}}Copy the code
Custom generic methods
The basic grammar
The modifier < T, R.. > Return type method name (parameter list) {}Copy the code
Generic methods can be defined in a generic class or in a generic class
Note that anyway generic methods have a <T,R.. Word-wrap: break-word! Important; “>
public void eat(T t){}// This is not a generic method, but uses generics
public <T,R> void eat(T T, R R){}/ / this is
Copy the code
Inheritance and wildcards for generics
Generics are not inheritable
package com.taoge.con;
import com.sun.tools.internal.xjc.reader.xmlschema.bindinfo.BIConversion;
import java.util.ArrayList;
public class Test {
// Can be polymorphic
Object o=new String("xx");
/ / error
// ArrayList<Object>list=new ArrayList<String>();
}
Copy the code
The wildcard
Act as a kind of restraint
<? >: supports any generic type <? Extends A> extends class A and subclasses of A, specifying the upper limit of generics <?superA>: Supports class A and its parent, not limited to the immediate parent, and specifies A generic lower boundCopy the code
In actual combat
package com.taoge.con;
import java.security.Key;
import java.util.*;
public class DAO<T> {
private Map<String,T> map=new HashMap<>();
// Get the ID object from the map
public T get(String id){
return map.get(id);
}
/ / replacement
public void update(String id,T entity){
map.put(id,entity);
}
// Return the T object stored in map
public List<T> lsit(a){
/ / create ArrList
ArrayList<T> list = new ArrayList<>();
//便利Map
Set<String> keyset = map.keySet();
for (String key:keyset){
list.add(map.get(key));
}
return list;
}
/ / delete
public void delete(String id){
map.remove(id);
}
/ / save
public void sava(String id,T entity){ map.put(id,entity); }}class Uesr{
private int id;
private int age;
private String name;
public Uesr(int id, int age, String name) {
this.id = id;
this.age = age;
this.name = name;
}
public int getId(a) {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge(a) {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName(a) {
return name;
}
public void setName(String name) {
this.name = name; }}/ / test
class Test{
public static void main(String[] args) {}}@Test
public void testlist(a){
DAO<Uesr>dao=new DAO<>();
dao.sava("111".new Uesr(1.19."jack"));
dao.sava("222".new Uesr(2.12."wewe"));
List<Uesr>list= dao.lsit();
System.out.println("list"+list);
// The rest is up
}
Copy the code