在HashMap中,当我尝试检索与密钥相关的值对时,我得到了整个列表

时间:2017-01-20 06:14:45

标签: java arraylist collections hashmap

在这个程序中,当我运行map.get(“b”)时,我得到整个列表,但我只想要与键“b”相关的值对。帮我解决一下。先谢谢!

    package test1;
    import java.util.*;
    public class Test1 {

        public static void main(String[] args) {
            Scanner in = new Scanner(System.in);//scanner object
            Map<String, List<Integer>> map = new HashMap<String, List<Integer>>();//map
            List<Integer> times = new ArrayList<Integer>();//arraylist

            int exit = 0;
            int stime;
            int etime;
            String [] letters = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
                "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"};
            for(int x = 0; exit == 0 ; x++){
                    System.out.println("Enter 1 -> ");
                    stime = in.nextInt();
                    System.out.println("Enter 2 --> ");
                    etime = in.nextInt();
                    if(stime == -1 || etime == -1){
                        exit = -1;
                    }
                    times.add(stime);
                    times.add(etime);
                    map.put(letters[x],times);
           }

            System.out.println(map.get("b"));

        }
}

1 个答案:

答案 0 :(得分:0)

问题是Arraylist times是在for循环之外初始化的。下面应该有用。

   for(int x = 0; exit == 0 ; x++){
            System.out.println("Enter 1 -> ");
            stime = in.nextInt();
            System.out.println("Enter 2 --> ");
            etime = in.nextInt();
            if(stime == -1 || etime == -1){
                exit = -1;
            }
            List<Integer> times = new ArrayList<Integer>();//arraylist
            times.add(stime);
            times.add(etime);
            map.put(letters[x],times);
   }

下面使用来自Apache Commons Lang库的Pair数据结构:

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);//scanner object
    Map<String, Pair> map = new HashMap<>();//map


    int exit = 0;
    int stime;
    int etime;
    String [] letters = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
        "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"};
    for(int x = 0; exit == 0 ; x++){
            System.out.println("Enter 1 -> ");
            stime = in.nextInt();
            System.out.println("Enter 2 --> ");
            etime = in.nextInt();
            if(stime == -1 || etime == -1){
                exit = -1;
            }
            map.put(letters[x],Pair.of(stime, etime));
   }

    System.out.println(map.get("b"));
}