简体   繁体   English

我可以用另一个集合初始化Java数组吗?

[英]Can I initialize a Java array with another collection?

I am working on a Java class that contains this field: 我正在研究包含以下字段的Java类:

private com.enel.xmlns.EDILM.SalReport.SalDettaglio[] sal;

this is an array. 这是一个数组。 Is it possibile initizialize this sal object with some other collection (a list) type in some way? 难道不可能性initizialize与其他一些集合(列表)型在某种程度上这SAL对象?

Tnx TNX

You might notice if you have a quick look at the Collecion javadoc that collections are supposed to implement a toArray method. 您可能会注意到,如果您对Collecion javadoc有所了解,那么集合应该实现toArray方法。

So yes, you can at anytime initialize an Array variable using the array returned by the toArray method of your collection. 所以是的,您可以随时使用集合的toArray方法返回的数组初始化Array变量。 (but you'll have to pay attention that the generic type of your collection correpond to the type of your array variable, and might have to cast what the toArray methods return to fit the type of your variable). (但您必须注意,集合的通用类型与数组变量的类型相对应,并且可能必须强制转换toArray方法返回的内容以适合您的变量类型)。

You would thus write something like : 因此,您将编写如下内容:

YourType[] sal= yourCollection.toArray(new YourType[0]);

如果有List则可以使用T [] toArray(T [] a)

这对您有用吗?

sal = myCollection.toArray(new com.enel.xmlns.EDILM.SalReport.SalDettaglio[myCollection.size()])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我可以在Java中初始化2D数组的数组/ arraylist <int>吗? - Can I initialize a array/arraylist<int> of 2D array in Java? 我可以在 JAVA 中用另一个全局变量初始化一个全局变量吗? - Can I initialize a global variable by another global variable in JAVA? 如何在 Java 中初始化长度为 0 的字符串数组? - How can I initialize a String array with length 0 in Java? 我可以在Java中使用相同的指令声明和初始化数组吗? - Can I declare and initialize an array with the same instruction in Java? 如何在 Java 中获取数组、集合或字符串的大小? - How can I get the size of an array, a Collection, or a String in Java? 我如何初始化另一个类的数组? - How do i initialize array of a another class? 如何创建and抽象类的数组,以便可以将其初始化为特定的非抽象类(java) - How can I create an array of and Abstract class such that I can initialize it to a specific non-abstract class (java) 如何使用 Java 中另一个类的构造函数初始化二维数组? - How do I initialize a 2D array using the constructor of another class in Java? Java嵌套parcelable,无法初始化数组 - Java nested parcelable, can't initialize an array 如何在Java中初始化数组? - How do I initialize an array in Java?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM