【问题标题】:Replacing an ArrayList item with a Linkedhashmap VALUE用 Linkedhashmap VALUE 替换 ArrayList 项
【发布时间】:2013-01-27 14:07:05
【问题描述】:

我有一个名为 numericValueMap 的 Linkedhashmap,它具有参数 String,String

{a=1,b=1,c=2,d=3,e=5}

我有一个名为 equation 的 Arraylist:

{ e, -, a, +, b, -, c, *, d, +, b}

我想要做的是用 Linkedhashmap 中的正确值替换 Arraylist 中的项目。到目前为止,这是我的尝试:

for (final String key: numericValueMap.keySet()) {
for (int i = 0, n = equation.size(); i < n; i++) {
String algebraItems = (String) equation.get(i);

if(algebraItems.contains(key)) {
    String newNum = algebraItems.replace(algebraItems, ?);
    equation.set(i,newNum);

  }
 }
 }

代码一直工作到并包括将 Arraylist 与相应的 Linkedhashmap Key 进行比较的点。但是,以我目前的知识,我无法用正确的值替换 Arraylist 项。关于我必须使用什么代码的任何想法?

【问题讨论】:

  • 您可以使用 get/set 在数组列表的一个循环中执行此操作。使用标准 for 循环,而不是增强型循环。
  • 得到它的工作谢谢。只需要使用迭代器和 get 方法。将尝试让它与 set 而不是 replace 一起工作。

标签: java arraylist linkedhashmap


【解决方案1】:

如果我理解正确的话-

int index =0;
if((index = arrayList.get(element))>=0)
    arrayList.set(index,replaceElement);

【讨论】:

  • 按照@Perception 的建议让它工作。现在将尝试您的方式,看看它是否满足我的需要。谢谢=D
【解决方案2】:

通过迭代 LinkedHashMap 并获得对每个项目 KEY 和 VALUE 的访问权限,如下所示:

for (Iterator<Entry<String, String>> it = numericValueMap.entrySet().iterator(); it.hasNext();) {
            Entry<String, String> e = it.next();
            String key = e.getKey();
            String value = e.getValue();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-24
    • 1970-01-01
    • 1970-01-01
    • 2019-04-01
    • 2015-02-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多