Iterator And Unmodifiable Wrappers,Null references

迭代器是一个对象,它遍历一组 元素并逐个返回元素。
Iterators are used under the covers in Java when you’re using a for (… : …) loop to step through a List or array. 遍历时默认调用迭代器
An iterator has two methods: – next() returns the next element in the collection — this is a mutator method! – hasNext() tests whether the iterator has reached the end of the collection.在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

注意,这不仅仅是MyIterator中的一个bug。ArrayList中的内置迭代器也遇到了同样的问题,for循环也是如此,这是它的语法糖。这个问题只是有一个不同的症状。如果你用这个代码代替:突变会破坏迭代器

不可修改的包装器通过拦截将修改集合的所有操作并抛出一个UnsupportedOperationException来取消修改集合的能力。
不可修改的包装器有两个主要用途,如下所示:一旦构建了集合,就使其不可变。在这种情况下,最好不要维护对支持集合的引用。这绝对保证了不变性。
允许某些客户机只读访问您的数据结构。您保留对支持集合的引用,但将引用分发给包装器。通过这种方式,客户端可以查看但不能修改,而您可以维护完全访问。

public class Student {
	 private String name;
	 private List<Course> courses;
	 public Student(String name,List<Course> courses>{
	  this.name=name; 
	  this.courses=courses; 
	  }
	public List<Course> getCourses() { 
	return courses;// ----->return Collections.unmodifiableList(courses);
	}
	public void setCourses(List<Course> courses) { 
	this.courses = courses; 
	}
}

在Java中,对对象和数组的引用也可以采用特殊的Null值,这意味着引用不指向对象。空值是Java类型系统中一个不幸的漏洞。
Primitives cannot be null and the compiler will reject such attempts with static errors:
原语不能为空,编译器将使用静态错误拒绝此类尝试
int size = null; //illegal
▪ Can assign null to any non-primitive variable, and the compiler happily accepts this code at compile time. But you’ll get errors at runtime because you can’t call any methods or use any fields with one of these references (throws NullPointerExceptions):
可以将null赋值给任何非原始变量,编译器在编译时欣然接受这段代码。但是在运行时您会得到错误,因为您不能调用任何方法或使用这些引用中的任何字段(抛出nullpointerexception)
String name = null;
name.length();
int[] points = null;
points.length;
▪ null is not the same as an empty string “” or an empty array.

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值