W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
可以創(chuàng)建一個(gè)包含在非泛型類中的通用方法。
public class Main { static <T, V extends T> boolean isIn(T x, V[] y) { for (int i = 0; i < y.length; i++) { if (x.equals(y[i])) { return true; } } return false; } public static void main(String args[]) { Integer nums[] = { 1, 2, 3, 4, 5 }; if (isIn(2, nums)){ System.out.println("2 is in nums"); } String strs[] = { "one", "two", "three", "four", "five" }; if (isIn("two", strs)){ System.out.println("two is in strs"); } } }
上面的代碼生成以下結(jié)果。
下面的代碼聲明一個(gè) copyList()
通用方法。
import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) { List<String> ls = new ArrayList<String>(); ls.add("A"); ls.add("B"); ls.add("C"); List<String> lsCopy = new ArrayList<String>(); copyList(ls, lsCopy); List<Integer> lc = new ArrayList<Integer>(); lc.add(0); lc.add(5); List<Integer> lcCopy = new ArrayList<Integer>(); copyList(lc, lcCopy); } static <T> void copyList(List<T> src, List<T> dest) { for (int i = 0; i < src.size(); i++) dest.add(src.get(i)); } }
構(gòu)造函數(shù)可以是通用的,即使它們的類不是。例如,考慮以下短程序:
class MyClass { private double val; <T extends Number> MyClass(T arg) { val = arg.doubleValue(); } void showval() { System.out.println("val: " + val); } } public class Main { public static void main(String args[]) { MyClass test = new MyClass(100); MyClass test2 = new MyClass(123.5F); test.showval(); test2.showval(); } }
上面的代碼生成以下結(jié)果。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: