[java] Adding to an ArrayList Java

I am a beginner to java, and need some help.

I am trying to convert an Abstract Data type Foo which is an associated list to an Arraylist of the strings B. How do you loop through the list and add each string to the array.

I may be over thinking it, but I am lost now.

Thanks for the help in advance.

This question is related to java arraylist

The answer is


If you have an arraylist of String called 'foo', you can easily append (add) it to another ArrayList, 'list', using the following method:

ArrayList<String> list = new ArrayList<String>();
list.addAll(foo);

that way you don't even need to loop through anything.


If you're using Java 9, there's an easy way with less number of lines without needing to initialize or add method.

List<String> list = List.of("first", "second", "third");

Well, you have to iterate through your abstract type Foo and that depends on the methods available on that object. You don't have to loop through the ArrayList because this object grows automatically in Java. (Don't confuse it with an array in other programming languages)

Recommended reading. Lists in the Java Tutorial


You should be able to do something like:

ArrayList<String> list = new ArrayList<String>();
for( String s : foo )
{
    list.add(s);
}

Array list can be implemented by the following code:

Arraylist<String> list = new ArrayList<String>();
list.add(value1);
list.add(value2);
list.add(value3);
list.add(value4);

Instantiate a new ArrayList:

List<String> myList = new ArrayList<String>();

Iterate over your data structure (with a for loop, for instance, more details on your code would help.) and for each element (yourElement):

myList.add(yourElement);

thanks for the help, I've solved my problem :) Here is the code if anyone else needs it :D

import java.util.*;

public class HelloWorld {


public static void main(String[] Args) {

Map<Integer,List<Integer>> map = new HashMap<Integer,List<Integer>>();
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(9);
list.add(11);
map.put(1,list);        

    int First = list.get(1);
    int Second = list.get(2);

    if (First < Second) {

        System.out.println("One or more of your items have been restocked. The current stock is: " + First);

        Random rn = new Random();
int answer = rn.nextInt(99) + 1;

System.out.println("You are buying " + answer + " New stock");

First = First + answer;
list.set(1, First);
System.out.println("There are now " + First + " in stock");
}     
}  
}