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;
}
}
运行结果如下: