Java多维初始化和循环添加
我试图将一个瞬态变量作为列表存储到模型中,下面是我的代码: 模型部件:Java多维初始化和循环添加,java,list,Java,List,我试图将一个瞬态变量作为列表存储到模型中,下面是我的代码: 模型部件: private List<String> combinedList = new ArrayList(); @Transient public List<String> getCombinedList() { return combinedList; } public void setCombinedList(List<String>
private List<String> combinedList = new ArrayList();
@Transient
public List<String> getCombinedList() {
return combinedList;
}
public void setCombinedList(List<String> combinedList) {
this.combinedList = combinedList;
}
问题:
1)我没有找到合适的add(ArrayList)方法,我不知道如何正确声明它
2)如果使用private List combinedList,我是否可以像下面这样存储多维值:
apple, banana
manggo, carrot
durian, kiwi
对于问题1: 我相信您想将ArrayList设置为combineList。在这种情况下,您需要使用
myJjjModel.setCombinedList(new ArrayList());
或
而不是
myJjjModel.getCombinedList().add(new ArrayList());
如果要在arrayList中添加字符串,可以执行以下操作
myJjjModel.getCombinedList().add("a1");
myJjjModel.getCombinedList().add(util.format(resutlMap.get("obj_Id")));
myJjjModel.getCombinedList().add(util.format(resutlMap.get("a1_date")));
myJjjModel.getCombinedList().addAll(List.of("a1",util.format(resutlMap.get("obj_Id")),util.format(resutlMap.get("a1_date"))));
或者,如果您使用的是Java9,则可以执行以下操作
myJjjModel.getCombinedList().add("a1");
myJjjModel.getCombinedList().add(util.format(resutlMap.get("obj_Id")));
myJjjModel.getCombinedList().add(util.format(resutlMap.get("a1_date")));
myJjjModel.getCombinedList().addAll(List.of("a1",util.format(resutlMap.get("obj_Id")),util.format(resutlMap.get("a1_date"))));
对于问题2:
不能在单个列表中存储多维值。在这种情况下,您可以使用以下选项
List<List<String>>
列表
我现在使用的是:
private ArrayList<ArrayList<String>> combinedList = new ArrayList<ArrayList<String>>();
@Transient
public ArrayList<ArrayList<String>> getCombinedList() {
return combinedList;
}
public void setCombinedList(ArrayList<ArrayList<String>> combinedList) {
this.combinedList = combinedList;
}
private ArrayList combinedList=new ArrayList();
@短暂的
公共ArrayList getCombinedList(){
返回组合列表;
}
public void setCombinedList(ArrayList combinedList){
this.combinedList=combinedList;
}
关于行动:
ArrayList<String> tempList = new ArrayList<String>();
tempList.add(myJjjModel.getObjectid());
tempList.add(util.format(resutlMap.get("a1_date")));
tempList.add(util.format(resutlMap.get("obj_Id")));
myJjjModel.getCombinedList().add(tempList);
ArrayList tempList=new ArrayList();
add(myJjjModel.getObjectid());
add(util.format(resutlMap.get(“a1_日期”));
add(util.format(resutlMap.get(“obj_Id”));
myjjmodel.getCombinedList().add(模板列表);
现在工作正常。
add(newarraylist())代码>你希望它做什么?您的列表是一个字符串列表,无法在其中添加数组。我正在尝试实际添加字符串,new ArrayList()
不完全是创建字符串的方式,我想您已经意识到了这一点。如果我尝试这样的操作:myjjmodel.getCombinedList().add(new list());它说:列表是抽象的,无法实例化。请尝试myJjjModel.getCombinedList().add(新建ArrayList(Arrays.asList(“xx”、“xx”、“xx”)));也不行