在 Java 中是否有将 ArrayList 转换为对象数组的命令?我知道如何将每个对象从 ArrayList 复制到对象数组中,但我想知道是否可以自动完成。
我希望像这样:
ArrayList<TypeA> a;
// Let's imagine "a" was filled with TypeA objects
TypeA[] array = MagicalCommand(a);
类似标准的Collection.toArray(T[])应该能够满足你的需求(请注意,ArrayList
实现了Collection
):
TypeA[] array = a.toArray(new TypeA[a.size()]);
顺便提一下,您应该考虑将a
定义为List<TypeA>
类型,而不是ArrayList<TypeA>
,这样可以避免一些实现特定的定义,可能并不适用于您的应用程序。
此外,请参见此问题关于使用a.size()
而不是0
作为传递给a.toArray(TypeA[])
的数组大小。
ArrayList<TypeA> a = new ArrayList<TypeA>();
Object[] o = a.toArray();
如果你想将该对象转换回TypeA,只需使用instanceOf方法进行检查即可。
将ArrayList转换为对象数组
ArrayList有一个接受Collection的构造函数,因此常见的做法是:
List<T> list = new ArrayList<T>(Arrays.asList(array));
这个方法构造了一个由数组创建的列表的副本。
现在,Arrays.asList(array)
会将数组包装起来,因此对列表的更改会影响数组,反之亦然。尽管您无法添加或删除
TypeA[] array = (TypeA[]) a.toArray();
String[]
强制转换为Object[]
,但反过来则不行。 - Christian Semrau使用这些库:
使用这段代码:
List<Object[]> testNovedads = crudService.createNativeQuery(
"SELECT cantidad, id FROM NOVEDADES GROUP BY id ");
Gson gson = new Gson();
String json = gson.toJson(new TestNovedad());
JSONObject jsonObject = new JSONObject(json);
Collection<TestNovedad> novedads = new ArrayList<>();
for (Object[] object : testNovedads) {
Iterator<String> iterator = jsonObject.keys();
int pos = 0;
for (Iterator i = iterator; i.hasNext();) {
jsonObject.put((String) i.next(), object[pos++]);
}
novedads.add(gson.fromJson(jsonObject.toString(), TestNovedad.class));
}
for (TestNovedad testNovedad : novedads) {
System.out.println(testNovedad.toString());
}
/**
* Autores: Chalo Mejia
* Fecha: 01/10/2020
*/
package org.main;
import java.io.Serializable;
public class TestNovedad implements Serializable {
private static final long serialVersionUID = -6362794385792247263L;
private int id;
private int cantidad;
public TestNovedad() {
// TODO Auto-generated constructor stub
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getCantidad() {
return cantidad;
}
public void setCantidad(int cantidad) {
this.cantidad = cantidad;
}
@Override
public String toString() {
return "TestNovedad [id=" + id + ", cantidad=" + cantidad + "]";
}
}
System.out.println(Arrays.toString(itemsList.toArray()));
- Azurespot