java map dot put 无法在 for 循环中工作

标签 java dictionary for-loop generics jvm

我是 Map 类的新手,我想知道我做错了什么。以下是我正在学习 map 的类(class)。

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 循环中检查了错误的谓词。这将完成这项工作:

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; 
  }
}

关于java map dot put 无法在 for 循环中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60101468/

相关文章:

python - 如何摆脱 Python 代码中的嵌套 for 循环?

JavaScript 库迭代器

bash - 为什么 'for' 循环比从文件读取的 'while' 循环更快?

java - 对密码进行安全 URL 编码

java - 如何编写需要密码才能满足某些要求的单一方法?

c# - C# 中允许重复键的字典的替代方案是什么?

python - 删除 python 字典中具有 nan 值的条目

java - 在java中创建字典?

Java 需要帮助实现算法

java - 是否可以在 Java 中获取未实例化变量的类型?