Java案例:泛型参数的方法
【摘要】
package net.hw.collection; import java.util.*; /** * Created by howard on 2018/2/2. */public class FindElementInCollection { public static void main(String[] args) {...
-
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;
-
}
-
}
运行结果如下:
文章来源: howard2005.blog.csdn.net,作者:howard2005,版权归原作者所有,如需转载,请联系作者。
原文链接:howard2005.blog.csdn.net/article/details/79335753
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)