Java泛型

xiaoxiao2021-02-28  78

直接看代码:

package com.ws.generic; import java.io.Closeable; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.List; /* * 非泛型方法中定义泛型方法 * 在返回类型前面<> * */ public class Method { // 泛型 public static <T> void show(T t){ System.out.println(t); } // 指定一个类型为List或者子类 public static <T extends List> void show(T t){ System.out.println(t.get(0)); } // 指定多个类型为Closeable或者子类 public static <T extends Closeable> void close(T... io){ for (T temp:io){ if (null!=temp){ try { temp.close(); } catch (IOException e) { e.printStackTrace(); } } } } public static void main(String[] args) throws FileNotFoundException { show("我是字符串"); List<String> list = new ArrayList<String>(); list.add("aaa"); show(list); FileInputStream in = new FileInputStream("test.txt"); close(in); } }

转载请注明原文地址: https://www.6miu.com/read-65284.html

最新回复(0)