每次我必须迭代一个集合时,我最终都会检查null,就在for-each循环的迭代开始之前.像这样:
if( list1 != null ){
for(Object obj : list1){
}
}
Run Code Online (Sandbox Code Playgroud)
是否有更短的方法,以便我们可以避免编写"if"块?注意:我使用的是Java 5,并且会在一段时间内坚持使用它.
在Java中,我们有Collections.emptyList()和Collections.EMPTY_LIST.两者都具有相同的属性:
返回空列表(不可变).此列表是可序列化的.
那么使用这一个或另一个之间的确切区别是什么?
我有两个活动,在第一个活动中,我实现了一个Object myObject的ArrayList.在第二项活动中,我需要得到这个Arraylist.我找到了一个教程:http://prasanta-paul.blogspot.com/2010/06/android-parcelable-example.html 我已经实现了我的课喜欢它的解释.
公共类Chapitre实现Parcelable {
private int numero;
private String titre;
private String description;
private int nbVideo;
private ArrayList<Video> listeVideo;
public Chapitre(int numero, String titre, String description,
ArrayList<Video> listeVideo) {
this.numero = numero;
this.titre = titre;
this.description = description;
this.listeVideo = listeVideo;
this.nbVideo = listeVideo.size();
}
//Getters and Setters ...
private Chapitre(Parcel source) {
numero = source.readInt();
titre = source.readString();
description = source.readString();
nbVideo = source.readInt();
source.readTypedList(listeVideo, Video.CREATOR);
}
@Override
public int describeContents() {
return 0;
} …Run Code Online (Sandbox Code Playgroud) 我试图了解创建列表的新实例之间的区别:
new ArrayList<X>
Run Code Online (Sandbox Code Playgroud)
和
Collections.emptyList();
Run Code Online (Sandbox Code Playgroud)
据我所知,后者返回一个不可变列表.这意味着无法添加,删除或修改它.我想知道为什么会创建和不可变的emptyList?有什么用?谢谢
如果我需要一个空列表,我可以使用
Arrays.asList()
Run Code Online (Sandbox Code Playgroud)
要么
Collections.emptyList()
Run Code Online (Sandbox Code Playgroud)
这两个电话有什么区别?我应该使用哪一个?