我需要创建一个Java数组列表(精确地说是一个向量),其中包含多个原始类型。
例如,我想在每个向量的行中看到以下内容:
row[0] --> "str1", 5, "str2", "str3", 3.5, 6, "str4"...etc...
row[1] --> "str5", 6, "str6", "str7", 5.3, 8, "str8"...etc...
你能帮助我吗?
谢谢!! :)
最佳答案
我认为这是解决您的问题的方法。我编写了一个适用于整数,字符串和浮点数的代码(其余代码可以完成)。
主(带有您的值)
public static void main(String[] args) {
//Init
ArrayList<ArrayList<Something>> mainList = new ArrayList<>();
ArrayList<Something> sublist1 = new ArrayList<>();
ArrayList<Something> sublist2 = new ArrayList<>();
//Fill array lists
sublist1.add(new Something("str1", 0));
sublist1.add(new Something(5, 1));
sublist1.add(new Something("str2", 0));
sublist1.add(new Something("str3", 0));
sublist1.add(new Something(3.5f, 2));
//etc
sublist2.add(new Something("str5", 0));
sublist2.add(new Something(6, 1));
sublist2.add(new Something("str6", 0));
sublist2.add(new Something("str7", 0));
sublist2.add(new Something(5.3f, 2));
//etc
//Add the two list in the main
mainList.add(sublist1);
mainList.add(sublist2);
//Iterator
int i = 0;
for (ArrayList<Something> sublist : mainList) {
i++;
System.out.println("Results from list " + i);
for (Something something : sublist) {
switch (something.getType()) {
case 0: {
System.out.println("String value: " + (String) something.getValue());
break;
}
case 1: {
System.out.println("Integer value: " + (Integer) something.getValue());
break;
}
case 2: {
System.out.println("Float value: " + (Float) something.getValue());
break;
}
}
}
}
}
类的东西:
public static class Something {
private Object value;
private int type;
/**
* Constructor of Something class
*
* @param value
* @param type type 0 String <br/>
* type 1 Integer <br/>
* type 2 float ....
*/
public Something(Object value, int type) {
this.value = value;
this.type = type;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
}
主要输出:
Results from list 1
String value: str1
Integer value: 5
String value: str2
String value: str3
Float value: 3.5
Results from list 2
String value: str5
Integer value: 6
String value: str6
String value: str7
Float value: 5.3