我写了代码:
List<String> Names = new ArrayList<String>();
List<Double> Prices = new ArrayList<Double>();
List<String> Dates = new ArrayList<String>();
List<String> Hours = new ArrayList<String>();
List<String> iDs = new ArrayList<String>();
SimpleAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView resultsListView = (ListView) findViewById(R.id.listMyReceipts);
SearchView m = (SearchView) findViewById(R.id.action_search);
HashMap<String, String> NamePrice = new HashMap<>();
TextView test = (TextView) findViewById(R.id.test);
Names.add("Starbucks"); Prices.add(11.99); Dates.add("01/01/2017"); Hours.add("9:33");
Names.add("Apple Store"); Prices.add(500.00); Dates.add("01/01/2017"); Hours.add("9:30");
Names.add("Esselunga"); Prices.add(135.67); Dates.add("01/01/2017"); Hours.add("11:51");
Names.add("Mediaworld"); Prices.add(19.98); Dates.add("01/01/2017"); Hours.add("12:03");
Names.add("Starbucks"); Prices.add(11.99); Dates.add("01/01/2017"); Hours.add("12:47");
for (int i = 0; i < Names.size(); i++) {
iDs.add(";+@:" + i + ":@+;");
NamePrice.put(iDs.get(i) + Names.get(i), " " + Prices.get(i).toString() + "€" + " - " + Dates.get(i) + " " + Hours.get(i));
}
List<HashMap<String, String>> listItems = new ArrayList<>();
adapter = new SimpleAdapter(this, listItems, R.layout.list_item,
new String[] {"First", "Second"},
new int[] {R.id.listitemTitle, R.id.listitemSubItem});
//Integer x = 0;
//int x = -1;
Iterator it = NamePrice.entrySet().iterator();
for (int i = 0; i < iDs.size(); i++) {
HashMap<String, String> resultMap = new HashMap<>();
Map.Entry pair = (Map.Entry) it.next();
resultMap.put("First", pair.getKey().toString().replace(iDs.get(i), ""));
resultMap.put("Second", pair.getValue().toString());
listItems.add(resultMap);
}
//test.setText(IDs.get(x - 1));
resultsListView.setAdapter(adapter);
}
这应该将所有ID替换为&#34;&#34;。它没有。所以输出可能是:; + @:0:@ +; NAME1 12.99; + @:1:@ +; NAME2 0.99 但是在第二个循环中,如果我说
resultMap.put("First", pair.getKey().toString().replace(IDs.get(0), ""));
它正确地替换了元素0。 输出将是:NAME1 12.99; + @:1:@ +; NAME2 0.99
答案 0 :(得分:0)
您没有按照预期的顺序获得NamePrice
的条目。我在您的第二个System.out.println()
循环中插入for
并按此顺序获取输出:
;+@:3:@+;Mediaworld
;+@:0:@+;Starbucks
;+@:4:@+;Starbucks
;+@:1:@+;Apple Store
;+@:2:@+;Esselunga
因此,您要尝试替换;+@:0:@+;
中的;+@:3:@+;Mediaworld
,依此类推。这不会取代任何东西。原因是NamePrice
是HashMap
。 HashMap
的迭代器不会以任何特定顺序返回条目,特别是不按插入顺序返回。
您可以改为使用LinkedHashMap
:
LinkedHashMap<String, String> NamePrice = new LinkedHashMap<>();
它的迭代器按照创建顺序返回条目。所以现在替换工作。