我是 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/