zoukankan      html  css  js  c++  java
  • Java泛型小随笔

    今天随便写写,大家都比较熟悉的基础知识(泛型),理论知识就不在这里细说了,请自行百度,直接上代码示例比较值观。

    1. 泛型-类 使用

    创建一个Entity实体类,如下:

    package com;
    
    public class SzlDemo<T> {
    	private T uName;
    	private T uPwd;
    	private T uAge;
    
    	public SzlDemo() {
    	}
    
    	public SzlDemo(T uName, T uPwd, T uAge) {
    		this.uName = uName;
    		this.uPwd = uPwd;
    		this.uAge = uAge;
    	}
    
    	public T getuName() {
    		return uName;
    	}
    	public void setuName(T uName) {
    		this.uName = uName;
    	}
    	public T getuPwd() {
    		return uPwd;
    	}
    	public void setuPwd(T uPwd) {
    		this.uPwd = uPwd;
    	}
    	public T getuAge() {
    		return uAge;
    	}
    	public void setuAge(T uAge) {
    		this.uAge = uAge;
    	}
    }
    

    main函数测试

    package com;
    
    public class Test1 {
    
    	public static void main(String[] args) {
    		// 泛型类 使用
    		SzlDemo<String> demo = new SzlDemo<String>("sss", "bbb", "16");
    		System.out.println(demo.getuName() + " : " + demo.getuAge());
    	}
    }
    

    2. 泛型-接口 使用

    创建接口定义

    package com.api;
    
    public interface SzlDemoApi<T> {
    	T getMsg(T msg);
    }
    

     接口实现类

    package com.api.impl;
    
    import com.api.SzlDemoApi;
    
    public class SzlDemoApiImpl implements SzlDemoApi<String> {
    
    	@Override
    	public String getMsg(String msg) {
    		return "这是泛型案例,返回信息为:" + msg;
    	}
    	
    }
    

     main函数测试

    package com;
    
    import com.api.SzlDemoApi;
    import com.api.impl.SzlDemoApiImpl;
    
    public class Test1 {
    
    	public static void main(String[] args) {
    		// 泛型接口 使用
    		SzlDemoApi<String> szlDemoApi = new SzlDemoApiImpl();
    		String resutlMsg = szlDemoApi.getMsg("haha, 冲啊!!!");
    		System.out.println(resutlMsg);
    	}
    }
    

    3. 泛型-方法 使用

    创建一个类,定义一个数字加法的方法

    package com;
    
    public class SzlDemo2 {
    
    	public static <T extends Number> Double calPlus(T a, T b) {
    		return a.doubleValue() + b.doubleValue();
    	}
    }
    

      main函数测试

    package com;
    
    import com.api.SzlDemoApi;
    import com.api.impl.SzlDemoApiImpl;
    
    public class Test1 {
    
    	public static void main(String[] args) {
    		// 泛型方法 使用
    		int t1 = 3, t2 = 6;
    		System.out.println("Integer类型相加为:" + SzlDemo2.calPlus(t1, t2).intValue());
    	}
    }
    
  • 相关阅读:
    ADC推荐:测量Flash的视频消费行为 (转载)
    9.7Go之函数之递归函数
    9.8线性表之单链表
    9.7线性表之顺序表
    9.7顺序表之增、删、改、查
    9.8Go之函数之计算执行时间
    9.8Go之函数之宕机(panic)
    9.9Go语言内存缓存
    9.7Go之函数之处理RuntimeError
    9.7Go之函数之defer(延迟执行语句)
  • 原文地址:https://www.cnblogs.com/jimmyshan-study/p/12767100.html
Copyright © 2011-2022 走看看