Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding to an ArrayList Java

Tags:

java

arraylist

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.

like image 257
Brian Avatar asked Oct 28 '11 22:10

Brian


People also ask

How do you append to an ArrayList?

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.

How do you add an ArrayList to an ArrayList?

Approach: ArrayLists can be joined in Java with the help of Collection. addAll() method. This method is called by the destination ArrayList and the other ArrayList is passed as the parameter to this method. This method appends the second ArrayList to the end of the first ArrayList.

How do you add an element to a list in Java?

There are two methods to add elements to the list. add(E e): appends the element at the end of the list. Since List supports Generics, the type of elements that can be added is determined when the list is created. add(int index, E element): inserts the element at the given index.


2 Answers

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); 
like image 85
pcalcao Avatar answered Oct 19 '22 21:10

pcalcao


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.

like image 42
Mohammad Najar Avatar answered Oct 19 '22 19:10

Mohammad Najar