I am trying to make the following method to a generic method and got struck.
public static MyObject[] getObjectFromList(List<MyObject> inputList) {
if (inputList != null && inputList.size() > 0) {
return inputList.toArray(new MyObject[inputList.size()]);
} else {
inputList = new ArrayList<MyObject>();
MyObject obj = new MyObject();
inputList.add(obj);
return inputList.toArray(new MyObject[inputList.size()]);
}
}
and have the other method which is similar but it's MyObject2
public static MyObject2[] getObjectFromList(List<MyObject2> inputList) {
if (inputList != null && inputList.size() > 0) {
return inputList.toArray(new MyObject2[inputList.size()]);
} else {
inputList = new ArrayList<MyObject2>();
MyObject2 obj = new MyObject2();
inputList.add(obj);
return inputList.toArray(new MyObject2[inputList.size()]);
}
}
How do I make this as a single method which takes any object(myobject,myobject2) list and returns an array ?
You can't do it without changing method signature due to type erasure. If you can pass a Class
object identifying the desired type you can do something like this:
public static <T> T[] getObjectFromList(List<? extends T> inputList, Class<T> c) {
if (inputList == null || inputList.isEmpty()) {
inputList = new ArrayList<T>();
T obj = null;
try {
obj = c.newInstance();
} (Exception ex) {
throw new RuntimeException("Instantiation failed", ex);
}
inputList.add(obj);
}
return inputList.toArray(Array.newInstance(c, inputList.size()));
}
There is a method for that already - List.toArray()
.
However, generics in Java do not allow for creating array of generic types (generics are lost at runtime, so E[] e = new E[5]
is not possible . So if you want to have an array of a specific type, rather than Object[]
(which t he above method returns), use:
MyObject[] array = list.toArray(new MyObject[list.size()]);
Having "at least one object in the list" is a requirement I would very much question. It does not sound right. If you are really certain you want it, axtavt has provided the correct method.
Try this
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
System.out.println(list);
Integer[] array = listToArray(list);
for(Integer i : array) {
System.out.println(i);
}
}
@SuppressWarnings("unchecked")
public static <T> T[] listToArray(List<T> list) {
return listToArray(list, (Class<T>) list.get(0).getClass());
}
@SuppressWarnings("unchecked")
public static <T> T[] listToArray(List<T> list, Class<T> clazz) {
return list.toArray((T[]) Array.newInstance(clazz, 0));
}
Give the method a generic type parameter:
public <T> T[] getObjectFromList(List<T> c);
Or with objects of type MyObjectInterface:
public <T extends MyObjectInterface> T[] getObjectFromList(List<T> c);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.