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.
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.
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.
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.
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);
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With