2015-12-11 143 views
1

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

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(); 
    } 
} 
} 
+0

所有列表在HashMap中都是空的。 – Hydroxis

+0

您需要在将地图放入地图后每次初始化一个新的'ArrayList'。 – user1803551

回答

4

您只有一个列表,其中您在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); 
    } 
} 
+0

我试图将它作为参数添加到置换函数中,但我不确定如何编辑它,因为Java中没有指针。现在测试第一部分:) – Hydroxis

+0

[] - 我仍然得到空输出:| – Hydroxis

+0

@Hydroxis您是否删除了'tempList.clear()'语句?我测试了代码,它的工作原理。 – Eran