在AashMap中存储ArrayList

时间:2015-12-11 20:02:24

标签: java arraylist hashmap

我有以下代码。我想要做的是使用置换函数填充ArrayList,将该Array保存在HashMap中,并重新开始该过程(基本上用每个键的ArrayList填充HashMap)。我发布了下面的代码,但它不起作用。我认为这是因为它存储了与我声明的列表相同的引用,而不是复制它。我是一个C磨砂膏和Java新手,所以任何帮助都表示赞赏!

public class Anagrams 
{
    public static HashMap<String, ArrayList<String>> permutacii = new HashMap<String, ArrayList<String>>();
    public static ArrayList<String> tempList = new ArrayList<String>();


private static void permutation(String prefix, String str)
{
    int n = str.length();
    if (n == 0) 
        tempList.add(prefix);
    else 
    {
        for (int i = 0; i < n; i++)
            permutation(prefix + str.charAt(i), 
        str.substring(0, i) + str.substring(i+1));
    }
}

public static void main(String[] args) {
    findAll(System.in);
}

public static void findAll(InputStream inputStream) 
{
    Scanner scanner = new Scanner(inputStream);
    while(scanner.hasNextLine())
    {
        String line = scanner.nextLine();
        permutation("", line);
        permutacii.put(line, tempList);
        tempList.clear();
    }
}
}

1 个答案:

答案 0 :(得分:4)

您只有一个List,您可以在HashMap中存储多个引用。并且在每次迭代结束时清除List。

解决问题的一种可能方法:

while(scanner.hasNextLine())
{
    String line = scanner.nextLine();
    tempList = new ArrayList<String>();
    permutation("", line);
    permutacii.put(line, tempList);
}

虽然我认为如果你将tempList作为局部变量并将其作为参数传递给permutation方法,代码会更具可读性:

while(scanner.hasNextLine())
{
    String line = scanner.nextLine();
    ArrayList<String> tempList = new ArrayList<String>();
    permutation("", line, tempList);
    permutacii.put(line, tempList);
}

并相应地修改permutation

private static void permutation(String prefix, String str, ArrayList<String> tempList)
{
    int n = str.length();
    if (n == 0) 
        tempList.add(prefix);
    else 
    {
        for (int i = 0; i < n; i++)
            permutation(prefix + str.charAt(i),
                        str.substring(0, i) + str.substring(i+1),
                        tempList);
    }
}
相关问题