Java参数,是否允许未指定大小的参数列表?

Java参数,是否允许未指定大小的参数列表?,java,generics,Java,Generics,在一个我有“父对象和子对象”概念的系统中,我尝试过使用参数来提供完整的类型安全性。我可能不会保持这种参数化水平,因为编写参数太难看了。然而,我在概念上有这样的东西: ModelObject<BaseType extends ModelObject<BaseType, ChildType>, ChildType extends ModelObject<ChildType,?>> { abstract Set<ModelObject<?, Bas

在一个我有“父对象和子对象”概念的系统中,我尝试过使用参数来提供完整的类型安全性。我可能不会保持这种参数化水平,因为编写参数太难看了。然而,我在概念上有这样的东西:

ModelObject<BaseType extends ModelObject<BaseType, ChildType>, ChildType extends ModelObject<ChildType,?>> 
{

 abstract Set<ModelObject<?, BaseType>> getParents();

 //other logic
 }
private List<MyObject> getParents(MyObject... children) {
    List<MyObject> parents = new ArrayList<MyObject>();

    for(MyObject child : children) {
        parents.add(child.getParent());
    }

    return parents;
}
ModelObject
{

抽象集您的问题的细节有点不清楚,但要回答您更基本的问题“是否可以允许未指定大小的参数列表?”,那么简单的答案是肯定的。您可以在Java中使用可变长度参数列表;它被称为

如果您有一个MyObject接口和MyObject 1、MyObject 2等,所有类都实现该接口,那么您可以执行以下操作:

ModelObject<BaseType extends ModelObject<BaseType, ChildType>, ChildType extends ModelObject<ChildType,?>> 
{

 abstract Set<ModelObject<?, BaseType>> getParents();

 //other logic
 }
private List<MyObject> getParents(MyObject... children) {
    List<MyObject> parents = new ArrayList<MyObject>();

    for(MyObject child : children) {
        parents.add(child.getParent());
    }

    return parents;
}
private List getParents(MyObject…children){
List parents=new ArrayList();
for(MyObject子对象:子对象){
parents.add(child.getParent());
}
返回父母;
}
…或者(假设MyObject的此特定实现将其子对象存储在列表中):

public List getChildren(){
返回集合。不可修改列表(子项);
}
公共布尔hasChildren(MyObject…children){
返回parent.getChildren().containsAll(Arrays.asList(children));//
}

您可以传递一个子类列表,而不是单独传递每个子类。这样子类的数量可以是任意的,您就不需要重新实现每个类。您需要以不同的方式指定每个类的唯一原因是如果每个类都有根本性的不同。

我很困惑,您是否试图用类替换对象,以及子类用泛型替换集合?泛型和varargs不会混合。这不是正确的答案;正如我问的泛型与varargs不起作用。但我显然没有正确表达我的答案,因为每个人都误解了它。所以我选择这个作为对每个人的最佳答案,尽管我在问:)
void foo(Integer... x) {
    Integer x1 = x.length > 0 ? x[0] : 0; 
    Integer x2 = x.length > 1 ? x[1] : 0;//x2 is set to the value of the second string that was passed in
    //...
}