# help me with ArrayList method addAll



## virkjay (Nov 1, 2007)

Hi guys, I am trying to wrtie a method to add all elements of one ArrayList to another one. My code is
import java.util.*;
public class Purse
{
public Purse()
{
coins = new ArrayList<String>();
}
public void add(String coinName)
{
coins.add(coinName);
}
public String toString()
{
if(coins.size() == 0)
return "Purse[]";
String output = "Purse[";
for(String coin : coins)
{
output = output + coin + ",";
}
return output + "]";
}
public void transfer1(Object other)
{
Purse otherPurse = (Purse) other;
coins.addAll(otherPurse);
other = null;
}

private ArrayList<String> coins;
}

The error i got is Purse.java:41: cannot find symbol
symbol : method addAll(Purse)
location: class java.util.ArrayList<java.lang.String>
coins.addAll(otherPurse);
^
1 error

Tool completed with exit code 1

when i tried to do in simple way it is perfectly work which is

import java.util.*;
public class TransferArrayList
{
public static void main(String args[])
{
ArrayList<String> list = new ArrayList();
list.add("abc");
list.add("fda");
ArrayList<String> list1 = new ArrayList();
list1.addAll(list);
System.out.print(list1);
list.clear();
System.out.println(list);
}

}

Can some one please tell me where i m doing mistake.


----------



## Chicon (Jul 29, 2004)

Hi virkjay,

Welcome to TSG ! 

The following method is incorrect :

```
[SIZE=2][B]
    public void transfer1(Object other) {
        Purse otherPurse = (Purse) other;
        coins.addAll(otherPurse);
        other = null;
    }
[/B][/SIZE]
```
- the casting of Purse is simply wrong : Purse is not an ArrayList
- you may pass an Object as parameter to the method but you must test if the object is an instance of ArrayList<String>

BTW, it is better to respect the data type of the attribute you want to update

The following coding is more appropriate :


```
[SIZE=2][B]
    public void transfer1(ArrayList<String> other) {
        coins.addAll(other);
    }
[/B][/SIZE]
```


----------



## virkjay (Nov 1, 2007)

Thanks mate, it is realy helpful.


----------

