使用方法在 ArrayList 中循环 [英] Looping in ArrayLists with a Method

查看:39
本文介绍了使用方法在 ArrayList 中循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在很多帮助下,我开发了一种制作字谜并将它们添加到 ArrayList 的方法.

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);
    }
}

问题是当我尝试使用这个函数在一个循环中创建 ArrayLists 时,将 Strings 从一个 ArrayList 添加到另一个,我收到一条错误消息,提示我不能使用 void,并且方法 f() 为 void.

The problem is when I attempt to use this function to make ArrayLists in a loop that adds Strings 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
        }

让我再澄清一下:我想使用此函数将字谜的 ArrayList 插入另一个 ArrayList 中的每个位置.字谜列表源自从一个列表读取到另一个列表的 String.我尝试将方法更改为静态,但这不起作用,我还删除了方法中的 return; 一次,但这也不能解决它.

Let me clarify once more: I want to use this function to insert ArrayLists of anagrams into each position in another ArrayList. The anagram Lists are derived from Strings 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?

推荐答案

发生错误是因为方法 f()void,意思是:它没有返回任何可以添加到 ArrayList 的值.

The error happens because the method f() is void, meaning: it doesn't return any value that can be added to the ArrayList.

调用f()的结果保存在作为参数传递给fArrayList中,你可能应该使用 ArrayList 将其所有元素添加到 Lists.像这样:

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);
}

这篇关于使用方法在 ArrayList 中循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆