Home  >  Article  >  Java  >  What is the syntax for using generic classes in java

What is the syntax for using generic classes in java

WBOY
WBOYforward
2023-05-16 12:19:06748browse

1. Syntax

  类名<具体的数据类型> 对象名=new 类名<具体的数据类型>();

2.After Java 1.7, the after new does not need to be written. Generic classes do not support basic data types

Class name Object name=new Class name<>();

Instance

public class ManTest {
    public static void main(String[] args) {
        //在创建对象时就要给泛型标识指定具体的数据类型,这里我指定了String
        Gneeric gneeric=new Gneeric<>("adawddwadwa");
         String  key1 =  gneeric.getKey();
        System.out.println("Key1="+key1);//Key1=adawddwadwa
 
        Gneeric gneeric1=new Gneeric<>(123);
            int key2=gneeric1.getKey();
        System.out.println ("key2="+key2);//key2=123
        
        //泛型类在创建对象的时候是没有指定数据类型,将按照object类型操作
        Gneeric gneeric2=new Gneeric<>("awewaea");
        Gneeric gneeric3=new Gneeric<>(12121);
         Object key4 =gneeric3.getKey();
 
    }
}

The above is the detailed content of What is the syntax for using generic classes in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete