【问题标题】:java map dot put not working in a for loopjava map dot put在for循环中不起作用
【发布时间】:2020-05-22 21:11:35
【问题描述】:

我是 Map 类的新手,我想知道我做错了什么。以下是我正在学习地图的课程。

import java.util.*;  
public class Maptester{
  Map<Integer, String> map = new HashMap<Integer, String>();
  public Maptester(String[] x){
    for(int i = 0; i > x.length; i++) map.put(i, x[i]);
  }
  public Maptester(ArrayList<String> x){
    for(int i = 0; i > x.size(); i++) map.put(i, x.get(i));
  }
  public String toString(){
    String x = "";
    for(Map.Entry m:map.entrySet()){  
      x += (m.getKey()+" "+m.getValue()+"\n");
    } return x; 
  }
}

这是我正在使用的主类。

import java.util.*;
class Main {
  public static void main(String[] args) {
    String[] x = {"x", "y", "z"};
    Maptester b = new Maptester(x);
    System.out.print(b);
  }
}

这个输出什么都没有,由于某种原因,在顶部的 for 循环中什么都没有放在 map 中,我不明白为什么。

【问题讨论】:

  • for (int i = 0; i &gt; x.size(); i++)?简单的调试几乎可以立即解决这个问题。
  • 是的,检查你的循环。 > vs mkyong.com/java/how-to-loop-a-map-in-java
  • Map.Entry 应该被参数化。

标签: java dictionary for-loop generics jvm


【解决方案1】:

您在 for 循环中检查了错误的谓词。这将完成这项工作:

public class Maptester{
  Map<Integer, String> map = new HashMap<Integer, String>();
  public Maptester(String[] x){
    for(int i = 0; i < x.length; i++) map.put(i, x[i]);
  }
  public Maptester(ArrayList<String> x){
    for(int i = 0; i < x.size(); i++) map.put(i, x.get(i));
  }
  public String toString(){
    String x = "";
    for(Map.Entry m:map.entrySet()){  
      x += (m.getKey()+" "+m.getValue()+"\n");
    } return x; 
  }
}

【讨论】:

    【解决方案2】:

    在 for 循环中,您输入了错误的比较运算符“>”而不是“

    public Maptester(String[] x){
        for(int i = 0; i < x.length; i++) map.put(i, x[i]);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-03
      • 1970-01-01
      • 2017-04-13
      • 2013-12-31
      • 2021-09-07
      • 2017-01-14
      • 2011-07-21
      • 2016-02-05
      相关资源
      最近更新 更多