zoukankan      html  css  js  c++  java
  • 21 泛型

    泛型类泛型演示

    泛型可以指定某个特定的类,当使用这个类时,可以设定只传入某种类型的数据。

    package cn.xxx.Collection;
    
    public class CollectionTest {
    	public static void main(String[] args) {
    		MyCollection<String> mc = new MyCollection<>();//泛型的声明,这里的<String>相当于实参
    		mc.set("hello", 0);
    		String str = (String)mc.get(0);
    		System.out.println(str);
    	}	
    }
    
    class MyCollection<E>{//这里的<E>相当于形参
    	Object[] objs = new Object[10];
    	
    	public void set(E e,int index){
    		objs[index] = e;
    	}
    	
    	public E get(int index){
    		return (E)objs[index];
    	}
    }
    

      

    泛型方法演示

    使用泛型方法可以不必声明泛型类,泛型仅在被声明的方法内发生。

    泛型方法的声明

    [权限修饰符] [static] <E> [返回类型] 方法名(E e){
    
    }
    

      

    举个例子:

    public class GenericityMethod {
    	public static <E> void test(E e){
    		System.out.println(e);
    	}
    	public static void main(String[] args) {
    		test("我和你");
    		test(111);
    	}
    }
    

      

  • 相关阅读:
    很难理解的三个设计模式
    设计模式思考(转)
    AOP
    CAP理论(摘)
    DDBS
    NoSql
    Enterprise Library 企业库
    padright padleft
    Process ProcessThread Thread
    053374
  • 原文地址:https://www.cnblogs.com/Scorpicat/p/11958749.html
Copyright © 2011-2022 走看看