collection 的克隆

Set union:  t = s1 + s2
Set difference:  t = s1 – s2
Set intersection:  t = s1 & s2

刚做作业差点吧intersection方法写成difference了,还在double check了一下~

过程中遇到concurrent Exception,原来是在foreach的同时又在修改那个List。 遂决定克隆一下clone()方法至今不敢乱用,偶然看到原来可以直接new一个List,参数放入需要复制的List,就会自动iterate参数List并且复制过去。 Okay!以此类推,所以实现iterator interface的collection都可以这样。 

另外, Set中本来就有intersection和union和difference方法,不过之前先要copy:
addAll → union
retainAll → intersection
removeAll → difference

Set<Type> union = new HashSet<Type>(s1); 

Set<Type> intersection = new HashSet<Type>(s1); 

Set<Type> difference = new HashSet<Type>(s1); 


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s