containsAll for nCopies of object in List
containsAll for nCopies of object in List
我想检查一个 Arraylist 是否包含同一元素的 n 个副本。
问题是:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class testMain {
public static void main(String[] args) {
myClass myObject = new myClass("haha1");
ArrayList a = new ArrayList();
a.add(myObject);
a.add(new myClass("haha2"));
a.add(new myClass("haha3"));
List b;
b = Collections.nCopies(5, myObject);
System.out.println(a.containsAll(b)); //prints true
}
static private class myClass {
String a;
myClass(String a) {
this.a = a;
}
}
}
问题 1:列表 b
的大小大于列表 a
- 应该是错误的
问题 2:List b
有多个 myObject
对象(与 Lista
相反 - 应该是 false
由于 containsAll 的工作方式,这不起作用,因为我想查看对象 myObject
是否包含(在本例中)3 次列表 a
.
我知道我可以编写自己的方法来完全满足我的要求,但我想知道是否有适用于这种情况的开箱即用的解决方案,或者什么是最 "elegant" 的方式处理它。
编辑:删除了对我使用 myClass
的说明,因为它与给定的示例冲突。
使用 Collections.frequency(a,myObject) == 5
(如果您不介意 Collection
在 myObject
中有超过 5 个实例,则使用 Collections.frequency(a,myObject) >= 5
)。
int java.util.Collections.frequency(Collection c, Object o)
Returns the number of elements in the specified collection equal to the specified object. More formally, returns the number of elements e in the collection such that (o == null ? e == null : o.equals(e)).
我想检查一个 Arraylist 是否包含同一元素的 n 个副本。 问题是:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class testMain {
public static void main(String[] args) {
myClass myObject = new myClass("haha1");
ArrayList a = new ArrayList();
a.add(myObject);
a.add(new myClass("haha2"));
a.add(new myClass("haha3"));
List b;
b = Collections.nCopies(5, myObject);
System.out.println(a.containsAll(b)); //prints true
}
static private class myClass {
String a;
myClass(String a) {
this.a = a;
}
}
}
问题 1:列表 b
的大小大于列表 a
- 应该是错误的
问题 2:List b
有多个 myObject
对象(与 Lista
相反 - 应该是 false
由于 containsAll 的工作方式,这不起作用,因为我想查看对象 myObject
是否包含(在本例中)3 次列表 a
.
我知道我可以编写自己的方法来完全满足我的要求,但我想知道是否有适用于这种情况的开箱即用的解决方案,或者什么是最 "elegant" 的方式处理它。
编辑:删除了对我使用 myClass
的说明,因为它与给定的示例冲突。
使用 Collections.frequency(a,myObject) == 5
(如果您不介意 Collection
在 myObject
中有超过 5 个实例,则使用 Collections.frequency(a,myObject) >= 5
)。
int java.util.Collections.frequency(Collection c, Object o)
Returns the number of elements in the specified collection equal to the specified object. More formally, returns the number of elements e in the collection such that (o == null ? e == null : o.equals(e)).