假设我有两个Arraylist。
a.add("Isabella");
a.add("Angelina");
a.add("Pille");
a.add("Hazem");
b.add("Isabella");
b.add("Angelina");
b.add("Bianca");
a.retainAll(b);
这应该为Arraylist提供了以下元素:Isabella, Angelina, Pille, Hazem
。但是,当我尝试时,a.size()
我得到0。为什么?
我的输出:
[DEBUG] The Karate Kid
[DEBUG] The Day the Earth Stood Still
[DEBUG] The Pursuit of Happyness
[DEBUG] Justin Bieber: Never Say Never
[DEBUG] After Earth
[DEBUG] Independence Day
[DEBUG] Men in Black
[DEBUG] Men in Black II
[DEBUG] Hancock
[DEBUG] Shark Tale
[DEBUG] Made in America
[DEBUG] Six Degrees of Separation
[DEBUG] Jersey Girl
[DEBUG] The Legend of Bagger Vance
[DEBUG] Men in Black 3
[DEBUG] Seven Pounds
[DEBUG] Bad Boys II
[DEBUG] Bad Boys 3
[DEBUG] Enemy of the State
[DEBUG] Wild Wild West
[DEBUG] Hitch
[DEBUG] Ali
[DEBUG] I, Robot
[DEBUG] Live 8
[DEBUG] Where The Day Takes You
[DEBUG] Independence Day 3
[DEBUG] I, Robot 2
[DEBUG] The Pursuit of Happyness
[DEBUG] I Am Legend
[DEBUG] Independence Day 2
[DEBUG] After Earth
[DEBUG] Bad Boys
[DEBUG] Partners in Time: The Making of MIB 3
[DEBUG] David Blaine: Real or Magic
[DEBUG] Size: 0
第一部分是由贾登·史密斯(Jaden Smith)主演的电影,第二部分是由威尔·史密斯(Will Smith)主演的电影,我只想要兼具两者的电影。是retainAll()
这种工作的最佳方法是什么?
我怀疑您是在列表中而不是字符串中存储自己的类的实例。
retainAll
使用equals
方法比较内容。如果您要存储自己的类的实例,并且不覆盖该类equals
,它将比较引用。由于两个列表中没有相同的实例(而是包含相同值的不同实例),因此它将从第一个列表中删除所有电影。
您可以通过equals
在课堂上实施来防止这种情况。为此,您可以看一下这个答案。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句