I have a function which prints the strings which are anagrams of each other using the List interface in Java. This function return type cannot be changed(its from a coding interview archive).
public List<List<String>> Anagrams(String[] string_list) {
// Code here
ArrayList<ArrayList<String>> anagrams=new ArrayList<ArrayList<String>>();
String l[]=new String[string_list.length];
for(int i=0;i<l.length;i++)
{
char c[]=string_list[i].toCharArray();
Arrays.sort(c);
l[i]=new String(c);
}
HashMap<String,ArrayList<String>> hash=new HashMap<String,ArrayList<String>>();
for(int i=0;i<l.length;i++)
{
//check if anagram list exists
ArrayList<String> list=hash.get(l[i]);
//anagram present
if(list!=null)
{
list.add(string_list[i]);
}
else
{
ArrayList<String> x=new ArrayList<String>();
x.add(string_list[i]);
hash.put(l[i],x);
}
}
for(Map.Entry element:hash.entrySet())
{
ArrayList<String> value=(ArrayList<String>)element.getValue();//unchecked cast
anagrams.add(value);
}
return anagrams;
}
The code is not able to run because it not able to implement the List interface using ArrayList. I face the following error:
error: incompatible types: ArrayList<ArrayList<String>> cannot be converted to List<List<String>>
return anagrams;
What am I doing incorrectly in this program? I must return adhere to the function template.
> anagrams = new ArrayList<>();`
– khelwood Aug 12 '21 at 07:44