简体   繁体   English

将数据移动到不同的方法

[英]Moving data to different methods

I am trying to figure out how to save a data in a submethod several times.我试图弄清楚如何在子方法中多次保存数据。 For example the code below is creating and array of strings then the array is moved to an arraylist five times.例如,下面的代码正在创建字符串数组,然后将数组移动到数组列表五次。 How to make the program save all strings 5 times.如何让程序保存所有字符串 5 次。 With other words, if I print out the array list newList .How to get the following output?换句话说,如果我打印出数组列表newList如何获得以下输出?

word0, word1, word2, word3, word4, word0, word1, word2, word3, word4, word0, word1, word2, word3, word4, word0, word1, word2, word3, word4, word0, word1, word2, word3, word4. word0、word1、word2、word3、word4、word0、word1、word2、word3、word4、word0、word1、word2、word3、word4、word0、word1、word2、word3、word4、word0、word1、word2、word3、word4。

public static void main(String[] args) {
    String[] list = new String[5];
    for (int i = 0; i < list.length; i++) {
        list[i] = "word" + i;
    }
    for (int i = 0; i < 5; i++) {
        experiment(list);
    }
}

public static void experiment(String[] list) {
    ArrayList<String> arrList = new ArrayList<>();
    for (int i = 0; i < list.length; i++) {
        arrList.add(list[i]);
    }
    saveItAll(arrList);
}

public static ArrayList<String> saveItAll(ArrayList<String> counter) {
    ArrayList<String> newList = new ArrayList<>();
    newList = counter;
    System.out.println(newList);
    return newList;

}

You need to store it outside of the method and statically.您需要将它存储在方法之外并静态存储。

public class Test
{
    static List<String> newList = new ArrayList<>();

    public static void main(String[] args)
    {
        String[] list = new String[5];
        for (int i = 0; i < list.length; i++) {
            list[i] = "word" + i;
        }
        for (int i = 0; i < 5; i++) {
            experiment(list);
        }

        System.out.println(newList);
    }

    public static void experiment(String[] list)
    {
        List<String> arrList = new ArrayList<>();
        for (int i = 0; i < list.length; i++) {
            arrList.add(list[i]);
        }
        saveItAll(arrList);
    }

    public static void saveItAll(List<String> counter)
    {
        newList.addAll(counter);
    }
}

Another word here: You would not need the saveItAll method, since addAll is also doing the job here.另一个词是:您不需要 saveItAll 方法,因为 addAll 也在这里完成了这项工作。 Then you usually don't use Lists with there implementing type, you usually use the interface to define the type of it so the implementation would be switchable.然后你通常不使用带有实现类型的列表,你通常使用接口来定义它的类型,这样实现就可以切换。 That's what interfaces are for.这就是接口的用途。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM