Is there a command in java for conversion of an ArrayList into a object array. I know how to do this copyi开发者_如何学运维ng each object from the arrayList into the object array, but I was wondering if would it be done automatically.
I want something like this:
ArrayList<TypeA> a;
// Let's imagine "a" was filled with TypeA objects
TypeA[] array = MagicalCommand(a);
Something like the standard Collection.toArray(T[]) should do what you need (note that ArrayList
implements Collection
):
TypeA[] array = a.toArray(new TypeA[a.size()]);
On a side note, you should consider defining a
to be of type List<TypeA>
rather than ArrayList<TypeA>
, this avoid some implementation specific definition that may not really be applicable for your application.
Also, please see this question about the use of a.size()
instead of 0
as the size of the array passed to a.toArray(TypeA[])
You can use this code
ArrayList<TypeA> a = new ArrayList<TypeA>();
Object[] o = a.toArray();
Then if you want that to get that object back into TypeA just check it with instanceOf method.
Yes. ArrayList
has a toArray()
method.
http://java.sun.com/javase/6/docs/api/java/util/ArrayList.html
Convert an ArrayList to an object array
ArrayList has a constructor that takes a Collection, so the common idiom is:
List<T> list = new ArrayList<T>(Arrays.asList(array));
Which constructs a copy of the list created by the array.
now, Arrays.asList(array)
will wrap the array, so changes to the list
will affect the array, and visa versa. Although you can't add or remove
elements from such a list.
TypeA[] array = (TypeA[]) a.toArray();
Using these libraries:
- gson-2.8.5.jar
- json-20180813.jar
Using this code:
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 + "]";
}
}
精彩评论