创建数组:
{int,String},{String,String},{int,long},{String,boolean},{String,double},{int,class Car},{String,class Car}
转换为HashMap,TreeMap,LinkedHashMap
这是班车:
public class Car implements Comparable{
int id;
String car_name;
String number;
public Car(int id, String car_name, String number) {
this.id = id;
this.car_name = car_name;
this.number = number;
}
@Override
public String toString() {
return "Car{" +
"id='" + id + '\'' +
", car_name='" + car_name + '\'' +
", number='" + number + '\'' +
'}';
}
}
有我的代码:
public class Main {
private static HashMap<Integer,String> toHM(Object[][] a){
HashMap<Integer,String> h = new HashMap<>();
for (Object[] o : a){
h.put((Integer) o[0], (String) o[1]);
}
return h;
}
private static HashMap<Integer,String> toLHM(Object[][] a){
HashMap<Integer,String> h = new LinkedHashMap<>();
for (Object[] o : a){
h.put((Integer) o[0], (String) o[1]);
}
return h;
}
private static TreeMap<Integer,String> toTM(Object[][] a){
TreeMap<Integer,String> h = new TreeMap<>();
for (Object[] o : a){
h.put((Integer) o[0], (String) o[1]);
}
return h;
}
public static void main(String[] args) {
Object[][] a = new Object[2][2];
a[0][0] = 1;
a[0][1] = "test";
a[1][0] = 2;
a[1][1] = "other test";
HashMap<Integer,String> aHM = toHM(a);
HashMap<Integer,String> aLHH = toLHM(a);
TreeMap<Integer,String> aTM = toTM(a);
}
}
这是代码正确吗?可能,最好在代码中使用泛型? 我明白如何解决这个问题吗?
答案 0 :(得分:1)
检查一下:
@SuppressWarnings("unchecked")
public static <S, T1, T2> S convert(Object[] inputobject, Class<S> mapType,
Class<T1> keyType, Class<T2> valueType)
throws IllegalAccessException, InstantiationException {
Map<T1, T2> map = (Map<T1, T2>) mapType.newInstance();
map.put((T1) inputobject[0], (T2) inputobject[1]);
return (S) map;
}
示例输入:
Object[] obj = new Object[] { 1, "test" };
System.out.println(convert(obj, HashMap.class, Integer.class, String.class));
示例输出:
{1=test}
我希望这会奏效。
答案 1 :(得分:0)
以下是您的协助的伪代码
例如。
调用功能:
HashMap hMap = getMap(Object[][] a, HashMap.class);
方法签名:
private <R> R (Object[][] a,Class<R> responseClazz){
Map mp = new responseClazz();
.....
return mp;
}