day07 collection 和泛型中的注意事项 ***

1,collection
(1)用迭代器遍历数组的时候不能用对象名.remove()方法 删除数组中的元素,也不能添加,会出现线程并发异常,但是可以用迭代器.remove()的方法删除一个元素。

public class Test {
    public static void main(String[] args) {
        Collection<String> c = new ArrayList<>();
        c.add("123");
        Iterator<String> it = c.iterator();
        while (it.hasNext()){
            c.remove(it.next());//会报错,不能用集合.remove()删除
        }
    }
}

正确代码

public class Test {
    public static void main(String[] args) {
        Collection<String> c = new ArrayList<>();
        c.add("123");
        Iterator<String> it = c.iterator();
        while (it.hasNext()){
            it.next();
            it.remove();
        }
    }
}

2.泛型
(1)泛型中没有多态 ,<? extends Fu> 表示Fu是传入类型的上限,即可以传入Fu类型和Fu的子类类型,可无限向下扩展;

(2)<? super Zi> 表示Zi是传入类型的下限,即可以传入Zi类型和Zi的父类类型,可无限向上扩展;

补充:
频繁往外读取内容的,适合用上界Extends。
经常往里插入的,适合用下界Super。
泛型只参与编译,用于规范代码,不参与代码执行。

**(3)泛型无多态。

public class Test {
    public static void main(String[] args) {
        A<Animal> a = new A<dog>();  //错误
        A<dog> b = new A<dog>();   //正确
        A<? extends Animal> c = new A<dog>();//正确
        A<? super Animal> d = new A<dog>();//错误
    }
}
class Animal{
}
class dog extends Animal{
}

class A<Animal>{
}
发布了8 篇原创文章 · 获赞 3 · 访问量 110

猜你喜欢

转载自blog.csdn.net/weixin_43814245/article/details/105232388