我有一个两个数组列表,在单个索引处有多个值。我正在添加如下的值:
ArrayList<String> list1 = new ArrayList<String>();
list1.addAll(Arrays.asList("iFRa1wVJ","Breakfast","7:00am","8:30am"));
list1.addAll(Arrays.asList("JyvmCZhw","Lunch","1:00pm","3:00pm"));
list1.addAll(Arrays.asList("HR6ovPjE","Dinner","7:30pm","9:30pm"));
ArrayList<String> list2 = new ArrayList<String>();
list2.addAll(Arrays.asList("iFRa1wVJ","Breakfast1","9:00am","10:30am"));
list2.addAll(Arrays.asList("JyvmCZhw","Lunch","2:00pm","3:00pm"));
list2.addAll(Arrays.asList("HR6ovPjE","Dinner","8:30pm","9:30pm"));
预期结果如下:
iFRa1wVJ,Breakfast,7:00am,8:30am --> Breakfast1 is overwriiten as Breakfast from list1
JyvmCZhw,Lunch,1:00pm,3:00pm --> 2:00pm is overwriiten as 1:00pm from list1
HR6ovPjE,Dinner,7:30pm,9:30pm --> 8:30pm is overwriiten as 7:30pm from list1
我需要比较每个索引的值,并使用第一个列表的值更新第二个列表。如何比较每个索引中的列表。任何帮助将不胜感激。感谢。
答案 0 :(得分:2)
听起来好像最好使用Map
或Set
代替List。例如:
class Meal {
//You may want to store times in a different format, i.e. a long in millisecond
private final String name, startTime, endTime;
Meal(String name, String startTime, String endTime) {
this.name = name;
this.startTime = startTime;
this.endTime = endTime;
}
//getName(), getStartTime(), getEndTime()...
}
在你的地图上......
final Map<String, Meal> map = new HashMap<>();
map.put("iFRa1wVJ", new Meal("Breakfast","7:00am","8:30am"));
map.put("iFRa1wVJ", new Meal("Breakfast","9:00am","10:30am"));
第二个“早餐”将取代第一个“早餐”,因为它们共享相同的密钥。
答案 1 :(得分:1)
您希望在每个索引处有两个具有多个值的数组列表,但在原始代码中ArrayList<String>
只是一个在每个索引处都有一个String
对象的数组。所以我更改了数据结构以保存String
的列表。如果您真正想要做的就是使用相应索引list1
的值更新每个索引,您只需更新索引处的所有内容。
ArrayList<List<String>> list1 = new ArrayList<List<String>>();
list1.add(Arrays.asList("iFRa1wVJ", "Breakfast", "7:00am", "8:30am"));
list1.add(Arrays.asList("JyvmCZhw", "Lunch", "1:00pm", "3:00pm"));
list1.add(Arrays.asList("HR6ovPjE", "Dinner", "7:30pm", "9:30pm"));
ArrayList<List<String>> list2 = new ArrayList<List<String>>();
list2.add(Arrays.asList("iFRa1wVJ", "Breakfast1", "9:00am", "10:30am"));
list2.add(Arrays.asList("JyvmCZhw", "Lunch", "2:00pm", "4:00pm"));
list2.add(Arrays.asList("HR6ovPjE", "Dinner", "8:30pm", "9:30pm"));
for (int i = 0; i < list1.size(); i++) {
list2.set(i, list1.get(i));
}
System.out.println(list1);