java 构造函数里面的Array-List作为参数之一,如何新建对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10559996/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 01:33:38  来源:igfitidea点击:

Array-List inside constructor as one of the parameter, how to create a new object?

javaconstructorarraylist

提问by fra pet

i am having problem with a constructor that takes an arrayList as one of the arguments.

我遇到了一个将 arrayList 作为参数之一的构造函数的问题。

public class ItemisedProductLine extends ProductLine{

public static ArrayList<String> serialNumbers;

public ItemisedProductLine(String productCode, double recRetPrice, double salePrice, int quantity, String description, ArrayList<String> SerialNumbers){
    super( productCode,  recRetPrice,  salePrice,  quantity,  description);
    this.serialNumbers = serialNumbers;
}    

}

}

Now in my class Inventory i want to instantiate a new ItemisedProductLine and pass an arryList of serial number to the constructor

现在在我的类 Inventory 中,我想实例化一个新的 ItemisedProductLine 并将序列号的 arryList 传递给构造函数

ItemisedProductLine item = new ItemisedProductLine("productCode", 2600, 2490, 2, "descrpition", new ArrayList<String>("1233456", "6789123"));

Is this possible in Java? It seem to be not a common task to do, did not found any example.

这在Java中可能吗?这似乎不是一个常见的任务,没有找到任何例子。

As alternative i could have used an generic array instead of Array-List but then i can not initialize it because of the unknown size

作为替代方案,我可以使用通用数组而不是 Array-List 但由于未知大小,我无法初始化它

Let's hope i'm not forgetting another parenthesis :-)

让我们希望我不会忘记另一个括号:-)

Last Thing is the error is "no suitable constructor found ArraList<>"

最后一件事是错误是“找不到合适的构造函数ArraList<>”

回答by Edwin Dalorzo

You could try:

你可以试试:

new ArrayList<String>(Arrays.asList("1233456", "6789123"))

回答by Jake Biesinger

@Edwin's answer is good, but you could also ditch the ArrayListconstructor in favor of a simple cast. Arrays.asListalready creates a new ArrayListfor you.

@Edwin 的回答很好,但您也可以放弃ArrayList构造函数,转而使用简单的强制转换。Arrays.asList已经new ArrayList为您创建了一个。

(ArrayList<String>) Arrays.asList("1233456", "6789123")

(ArrayList<String>) Arrays.asList("1233456", "6789123")

回答by George Siggouroglou

There is another way using Java 8 Stream API.
You can create a Stream of objects and collect them as a List (or Set or whatever cause you can build your own collector).

还有另一种使用Java 8 Stream API 的方法
您可以创建对象流并将它们收集为 List (或 Set 或任何您可以构建自己的收集器的原因)。

Stream.of(
        new MyClassConstructor("supplierSerialNo", "supplierSerialNo", String.class),
        new MyClassConstructor("title", "title", String.class),
        new MyClassConstructor("kind", "kind", String.class))
.collect(Collectors.toList())