Java - 如何使用循环在HashMap中映射多个ArrayLists

时间:2013-12-27 05:38:41

标签: java arraylist hashmap

我正在做家庭作业(CS 106A, Handout #8)。这是一个旅行行程计划,用户选择一个来源并获得潜在目的地列表。

我被困在数据存储部分,我正在阅读文本文件(pdf的第2页)并存储它。我选择将数据存储在HashMap<String, ArrayList<String>>;其中密钥是旅行来源,价值为ArrayList,所有目的地都来自给定的来源。

这是我到目前为止的代码(https://gist.github.com/cch5ng/8139898

//imports

import acm.program.*;
import acm.io.*;
import acm.graphics.*;
import java.util.*;
import java.util.HashMap;
import java.util.Iterator;
import java.awt.event.*;
import java.awt.Color;
import java.awt.TextField;
import java.io.*;
import java.nio.file.*;
import java.nio.charset.*;
import javax.swing.*;
import javax.swing.event.MouseInputAdapter;

public class handout8 extends ConsoleProgram {

public void init() {
    //read in flights.txt data
    origin_old = "";
    Path file = Paths.get("flights.txt");
    Charset charset = Charset.forName("US-ASCII");
    try (BufferedReader reader = Files.newBufferedReader(file, charset)) {
        String line = null;
        while ((line = reader.readLine()) != null) {
            origin_new = "";
            //System.out.println("origin_old: " + origin_old + ".");
            dest = "";
            //destinations.clear();
            int k = 0;
            while (line.charAt(k) != 0 && k < line.length() - 1 && line.charAt(k + 1) != 45) { //45 for -
                origin_new += Character.toString(line.charAt(k));
                k++;
            }
            if (line.length() > 1) {
                System.out.println("k: " + k);
                System.out.println("origin_old: " + origin_old + ".");
                System.out.println("origin new: " + origin_new + ".");
                if (k != 0) {
                    dest = line.substring(k + 3);
                }
                //issue here where all the keys end up with the same destinations array list
                //I know I can correctly get the number of origin cities, so maybe I need to hardcode the array list names somehow?
                if (origin_old.equals(origin_new)) {
                    destinations.add(dest);
                    System.out.println("added dest");
                } else {
                    destinations.clear();
                    System.out.println("cleared dest");
                    destinations.add(dest);
                }
                System.out.println("dest: " + dest);
                System.out.println("num destinations: " + destinations.size());
                //error in logic adding data to hashmap
                //issue here where all the keys end up with the same destinations array list
                //ArrayList<String> destin_old = new ArrayList<String>();
                //destin_old = destinations;
                if (!origin_new.equals("")) {
                    mp_destinations.put(origin_new, destinations);
                }

                origin_old = origin_new;
                printDest(origin_new);
            }
        }
    } catch (IOException e) {
        println("IOException: " + e);
    }
    printKeys();
    printDest("Denver");
    printDest("New York");
    //printDest("San Francisco");
    //printDest("San Jose");
    //printDest("Honolulu");
    //printDest("Anchorage");
}

private void printKeys() {
    Iterator it = mp_destinations.keySet().iterator();
    System.out.println("Origins: ");
    while (it.hasNext()) {
        System.out.println(it.next());
    }
}

private void printDest(String start) {
    ArrayList<String> dest2 = mp_destinations.get(start);
    if (dest2.size() > 1) {
        Iterator i = dest2.iterator();
        System.out.println("Destinations for " + start + ": ");
        while (i.hasNext()) {
            System.out.println(i.next());
        }
    } else {
        System.out.println("Destination for " + start + ": " + dest2.get(0));
    }
}
//ivars
private ArrayList<String> destinations = new ArrayList<String>();
private HashMap<String, ArrayList<String>> mp_destinations = new HashMap<String, ArrayList<String>>();
private String origin_old, origin_new, dest;
}

(问题似乎在第50-67行) 循环遍历文本文件的行时,程序似乎正在适当地定义键和相应的ArrayList内容。但是,当我在最后检查HashMap的值时,所有返回的值仅适用于添加的最后一个键。我猜所有的键似乎都映射到同一个ArrayList。

我是否需要为每个键的密钥对唯一的ArrayList进行硬编码?如何为每个键定义和维护不同的ArrayLists(动态)(假设在运行程序之前我不知道键的数量)? TIA。

2 个答案:

答案 0 :(得分:1)

您需要为地图的每个键指定一个全新的ArrayListdestinations。否则,键将全部映射到同一对象。

替换此行:

destinations.clear();

destinations = new ArrayList<String>();

答案 1 :(得分:0)

你似乎误用了HashMap put方法。 无论何时调用map.put,都要用给定的新值替换存储的当前值。 请考虑以下代码段

ArrayList<String> destinations = new ArrayList<String>();
//add new destination
destinations.add("dest1");
destinations.add("dest2");

if (!origin_new.equals("")) {
    //before adding to map obtain the current list of destinations
    ArrayList<String> currentDestinations = mp_destinations.put(origin_new);
    if (currentDestinations == null)
        //if the origin doesn't exists, create the destinations list
        currentDestinations = new ArrayList<String>();

    //add all the new destinations to the list
    currentDestinations.addAll(destinations);

    //store the modified list in your map
    mp_destinations.put(origin_new, currentDestinations);                   
}