[英]ArrayList as a Value to HashMap returns only last element of ArrayList
请参阅以下代码-
Map<DateTime, ArrayList<ElementInformationBean>> mapTithi = new HashMap<DateTime, ArrayList<ElementInformationBean>>();
List<ElementInformationBean> lstTime = null;
ElementInformationBean curntTithi = null;
ElementInformationBean nextTithi = null;
for (int i = 0; i < lstNakstra.size()-1; i++) {
lstTime = new ArrayList<ElementInformationBean>();
curntTithi = lstNakstra.get(i);
nextTithi = lstNakstra.get(i+1);
if(curntTithi.getStartTime().toDateMidnight().equals(nextTithi.getStartTime().toDateMidnight()))
{
lstTime.add(curntTithi);
lstTime.add(nextTithi);
mapTithi.put(curntTithi.getStartTime().toDateMidnight().toDateTime(), (ArrayList<ElementInformationBean>) lstTime);
} else {
lstTime.add(curntTithi);
mapTithi.put(curntTithi.getStartTime().toDateMidnight().toDateTime(), (ArrayList<ElementInformationBean>) lstTime);
}
}
印刷用
for (Map.Entry<DateTime, ArrayList<PanchangaElementInformationBean>> entry : mapTithi.entrySet()) {
DateTime key = entry.getKey();
ArrayList<PanchangaElementInformationBean> values = entry.getValue();
System.out.println("Key = " + key);
for (PanchangaElementInformationBean p: values) {
System.out.print("Values = " + p.getStartTime() + "n");
}
}
我正在尝试使用HashMap; 键为dateTime,值为List。 但是,当我迭代并打印该值时,它总是返回。
感谢Kumar Shorav
在循环外初始化lstTime
。
试试这个代码:
Map<DateTime, ArrayList<ElementInformationBean>> mapTithi = new HashMap<DateTime, ArrayList<ElementInformationBean>>();
// Intialize here
List<ElementInformationBean> lstTime = new ArrayList<ElementInformationBean>();
ElementInformationBean curntTithi = null;
ElementInformationBean nextTithi = null;
for (int i = 0; i < lstNakstra.size()-1; i++) {
curntTithi = lstNakstra.get(i);
nextTithi = lstNakstra.get(i+1);
if(curntTithi.getStartTime().toDateMidnight().equals(nextTithi.getStartTime().toDateMidnight()))
{
lstTime.add(curntTithi);
lstTime.add(nextTithi);
mapTithi.put(curntTithi.getStartTime().toDateMidnight().toDateTime(), (ArrayList<ElementInformationBean>) lstTime);
} else {
lstTime.add(curntTithi);
mapTithi.put(curntTithi.getStartTime().toDateMidnight().toDateTime(), (ArrayList<ElementInformationBean>) lstTime);
}
}
在PanchangaElementInformationBean
类的Getters
和Setters
上,将数据类型从Date
更改为ArrayList<Date>
,并将该setStartTime
添加到下面,以便可以从中获取所有值。
private ArrayList<Date> startTime;
public ArrayList<Date> getStartTime() {
return startTime;
}
public void setStartTime(Date item) {
if (startTime == null) {
startTime = new ArrayList<Date>();
}
this.startTime.add(item);
}
因此,当您迭代时,您可以从ArrayList
获取所有值
并将其添加到主打印for loop
以从ArrayList
打印单个Date
for (Date startTime : p.getStartTime()) {
System.out.println(startTime);
}
并初始化lstTime = new ArrayList<ElementInformationBean>();
在For循环上方,以便您可以添加许多元素,否则它将仅向循环添加一个for循环实例值。
如果要在列表中累积用作地图值的元素,则必须使用以下方法:
List<...> list = map.get( key );
if( null == list ) {
list = new ...;
map.put( key, list );
}
list.add( ... );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.