I have this ArrayList in Java -
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
To convert it to an array I invoke list.toArray()
method, but it returns Object[]
. This is not what I want. I want Map<String, Object>[]
.
I know about List.toArray(T[] a);
It doesn't work with parameterized types.
The method signature of batchUpdate method in Spring framework is this -
int[] org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate.batchUpdate(String sql, Map<String, ?>[] batchValues)
If it is not possible to create array of Map objects why is Spring using it? And how are we supposed to use this method then?
In a nutshell, you can't make arrays of concrete parameterized types. This is a pretty good explanation of what's going on. The Spring type is essentially the same as saying Map batchValues
. The parameter types are for documentation only. This gaping hole in the Java type system is a tradeoff for performance.
试试这个,
Map<String,Object>[] ar=list.toArray(new HashMap[list.size()]);
你可以尝试这样:
Map<String, Object> [] mp = list.toArray(new HashMap[list.size()]);
Do it this way:
Map<String, Object> [] mp = new HashMap[list.size()];
list.toArray(mp);
This answer works. I tested it.
My full test code is as follows:
import java.util.*;
public class Test {
public static void main (String [] args) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("Hello", "World");
ArrayList<Map<String, Object>> list = new ArrayList<Map <String, Object>>();
list.add(map);
Map<String, Object> [] mp = new HashMap[list.size()];
list.toArray(mp);
System.out.println(mp[0]); // prints out {Hello=World}
}
}
HashMap [] map = list.toArray(new HashMap [0]);
You can't do it.
List.toArray(T[] a) is your only option, but it does not work with parameterized types because they are not preserved at runtime.
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.