help me with ArrayList method addAll

Status
This thread has been Locked and is not open to further replies. Please start a New Thread if you're having a similar issue. View our Welcome Guide to learn how to use this site.

virkjay

Thread Starter
Joined
Nov 1, 2007
Messages
10
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.
 
Joined
Jul 29, 2004
Messages
6,650
Hi virkjay,

Welcome to TSG ! :)

The following method is incorrect :
Code:
[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 :

Code:
[SIZE=2][B]
    public void transfer1(ArrayList<String> other) {
        coins.addAll(other);
    }
[/B][/SIZE]
 
Status
This thread has been Locked and is not open to further replies. Please start a New Thread if you're having a similar issue. View our Welcome Guide to learn how to use this site.

Users Who Are Viewing This Thread (Users: 0, Guests: 1)

As Seen On
As Seen On...

Welcome to Tech Support Guy!

Are you looking for the solution to your computer problem? Join our site today to ask your question. This site is completely free -- paid for by advertisers and donations.

If you're not already familiar with forums, watch our Welcome Guide to get started.

Join over 807,865 other people just like you!

Latest posts

Staff online

Members online

Top