Java案例:泛型参数的方法

xiaoxiao2021-02-28  15

package net.hw.collection; import java.util.*; /** * Created by howard on 2018/2/2. */ public class FindElementInCollection { public static void main(String[] args) { List<String> names = new ArrayList<>(); names.add("mike"); names.add("howard"); names.add("smith"); names.add("alice"); names.add("brown"); names.add("green"); String name = "alice"; if (contains(names, name)) { System.out.println(name + " is in " + names); } else { System.out.println(name + " is not in " + names); } /// Set<Integer> nums = new HashSet<>(); for (int i = 0; i < 10; i++) { nums.add(new Random().nextInt(100)); } Integer num = 25; if (contains(nums, num)) { System.out.println(num + " is in " + nums); } else { System.out.println(num + " is not in " + nums); } } /** * 查看任意集合是否包含指定元素泛型方法 */ public static <E> boolean contains(Collection<E> c, Object obj) { for (E element : c) { if (element.equals(obj)) { return true; } } return false; } } 运行结果如下:
转载请注明原文地址: https://www.6miu.com/read-2630042.html

最新回复(0)