我的旧代码中包含以下代码段。在这里,它使用枚举来迭代两个哈希表。
public View getView(int position, View convertView, ViewGroup parent) {
//controllo se c'è gia un layout
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
//if (convertView == null) {
convertView = mInflater.inflate(R.layout.libretto_element, null);
librettoDTO content = getItem(position);
TextView textTitolo = convertView.findViewById(R.id.nome_materia);
textTitolo.setText(content.getTitolo());
Toast.makeText(getContext(), content.getTitolo()+"", Toast.LENGTH_LONG).show();
//}
return convertView;
}
理想期望如下;
0
1
2
++ 0
++ 1
++ 2
但是,以上代码打印为;
2
1
0
2
1
0
问题,我可以在这里看到,当循环第二个Hashtable时,Enumeration不会重置。我想知道这种行为的原因。是的,当然,最新版本的Java具有更有效的循环方式。
答案 0 :(得分:0)
您只打印哈希表键而不是值
Hashtable h4 = new Hashtable();
Hashtable h5 = new Hashtable();
for (int i=0 ; i < 3; i++) {
h4.put (i, "" + i);
//System.out.println(h4.get(i));
}
for (int i=0 ; i < 3; i++) {
h5.put (i, "++"+i);
//System.out.println(h5.get(i));
}
// java8 functionality
//h4.values().stream().forEach(System.out::println);
//h5.values().stream().forEach(System.out::println);
//if legacy one iterator
Iterator enum1 = h4.values().iterator();
while(enum1.hasNext()) {
System.out.println(enum1.next());
}
enum1 = h5.values().iterator();
while(enum1.hasNext()) {
System.out.println(enum1.next());
}