Java案例:泛型参数的方法

Java案例:泛型参数的方法_第1张图片

package net.hw.collection;

import java.util.*;

/**
 * Created by howard on 2018/2/2.
 */
public class FindElementInCollection {
    public static void main(String[] args) {
        List 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 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  boolean contains(Collection c, Object obj) {
        for (E element : c) {
            if (element.equals(obj)) {
                return true;
            }
        }
        return false;
    }
}
运行结果如下:
Java案例:泛型参数的方法_第2张图片

你可能感兴趣的:(Java案例:泛型参数的方法)