简体   繁体   中英

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. With other words, if I print out the array list newList .How to get the following output?

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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