- package com.review.demo2;
- import java.util.ArrayList;
- import java.util.Collection;
- import java.util.HashSet;
- import java.util.Iterator;
- import java.util.List;
- import java.util.Set;
- /**
- * 案例3:向不同集合中,存储不同的类型的对象。 存储:Student、Worker
- *
- */
- public class ConstraintTypeDemo5 {
- public static void main(String[] args) {
- // 创建一个List集合,存放Dog
- List<Dog>list1 = new ArrayList<>();
-
- //创建一个Set集合,存放Cat
- Set<Cat> set = new HashSet<>();
-
- //存储相同了类型的元素
-
- list1.add(new Dog("kitty",2));
- list1.add(new Dog("jimmy",1));
- list1.add(new Dog("jone",3));
- list1.add(new Dog("lasha",5));
-
- printCollection(list1);
- System.out.println("-------------------------------------------------------------");
- set.add(new Cat("mouse",2));
- set.add(new Cat("cat",1));
- set.add(new Cat("cat2",3));
- printCollection(set);
- }
-
- //创建一个输出集合的功能 Collection<?>?相当于Object
- public static void printCollection(Collection <?>coll){
-
- //way1遍历
- /*for (int i = 0; i < list.size(); i++) {
- System.out.println(list.get(i));
- }*/
-
- //way2遍历
- for (Iterator <?>it = coll.iterator();it.hasNext();) {
- Object obj = it.next();//此处由于添加了通配符,Object可能是Dog,也可能是Cat
- if (obj instanceof Dog) {
- Dog dog = (Dog)obj;
- System.out.println(dog);
- }else if(obj instanceof Cat){
- Cat cat = (Cat)obj;
- System.out.println(cat);
- }
- }
- }
- }
复制代码 |
|