A simple example of a Java generic

  • 2020-04-01 02:18:33
  • OfStack


package com.chase.test;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
public class testT {
    public static <T> void main(String[] args) {
        testT classT = new testT();
        List<T> find = classT.find(0, 10);
        if (find != null && find.size()>0) {
            for (T integer : find) {
                System.out.println(integer);
            }
        }
//        showList();
    }

    public static <T> void showList() {
        testT classT = new testT();
        List<T> find = classT.find(0, 10);
        for (T t : find) {
            System.out.println(t);
        }
    }

    public <T> List<T> find(int begin, int end) {
        List<T> list = new ArrayList<T>();
        list.add((T)new Integer(222));
        list.add((T)"111");
        list.add((T)" Yesterday was the double ninth festival! ");
        return list;
    }
}
 
class TestGen0<K,V>{ 
      public Hashtable<K,V> h=new Hashtable<K,V>(); 
      public void put(K k, V v) { 
       h.put(k,v); 
      } 
      public V get(K k) { 
       return h.get(k); 
      } 
      public static void main(String args[]){ 
       TestGen0<String,String> t=new TestGen0<String,String>(); 
       t.put("key", "value"); 
       String s=t.get("key"); 
       System.out.println(s); 
      } 
    }

TestT output:

222
111
Yesterday was the double ninth festival!

TestGen0 output:
The value


Related articles: