我有以下代码。我想要做的是使用排列函数填充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();
}
}
}
所有列表在HashMap中都是空的。 – Hydroxis
您需要在将地图放入地图后每次初始化一个新的'ArrayList'。 – user1803551