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.


Solution 1:

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

Solution 2:

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.

Solution 3:

You should be able to do something like:

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

Solution 4:

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

Solution 5:

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