问题
With much assistance I have developed a method that makes anagrams and then adds them into an ArrayList
.
public void f(String s, String anagram, ArrayList<String> array)
{
if(s.length() == 0)
{
array.add(anagram);
return;
}
for(int i = 0 ; i < s.length() ; i++)
{
char l = s.charAt(i);
anagram = anagram + l;
s = s.substring(0, i) + s.substring(i+l, s.length());
f(s,anagram,array);
}
}
The problem is when I attempt to use this function to make ArrayList
s in a loop that adds String
s from one ArrayList
to another, I get an error saying I can't use a void, and the method f()
is void.
List<String> Lists = new ArrayList<String>(); //makes new array list
for(String List : words)
{ //takes values from old array list
List.trim();
Lists.add(f(List,"",new ArrayList<String>())); //this is where it doesn't work
}
Let me clarify once more:
I want to use this function to insert ArrayList
s of anagrams into each position in another ArrayList
. The anagram Lists are derived from String
s that are being read from one list to another. I tried changing the method to static but that doesn't work, I also removed the return;
in the method once, but that doesn't fix it either.
How do I make this whole thing work?
回答1:
The error happens because the method f()
is void
, meaning: it doesn't return any value that can be added to the ArrayList
.
The answer of invoking f()
is stored in the ArrayList
passed as a parameter to f
, you should probably use that ArrayList
to add all of its elements to Lists
. Something like this:
List<String> lists = new ArrayList<String>();
for (String list : words) {
list.trim();
ArrayList<String> answer = new ArrayList<String>();
f(list, "", answer);
lists.addAll(answer);
}
回答2:
Your method header for F needs to look like this:
public String f(String s, String anagram, ArrayList<String> array)
And then you return a String value to add to that ArrayList you are using.
回答3:
Your function definition for f()
shows the return value of type void
. So looking at your code you're attempting to do this:
Lists.add(void);
which is obviously illegal.
Your choice really is to have the ArrayList declared in a greater scope.
private List<String> anagrams;
public void f(String s, String anagram) {
...
anagrams.add(anagram);
...
}
....
for(String List : words) {
//takes values from old array list
anagrams = new ArrayList<String>();
List.trim();
f(list,"");
Lists.add(anagrams); //this is where it doesn't work
}
来源:https://stackoverflow.com/questions/15396858/looping-in-arraylists-with-a-method