mrprogrammer231
mrprogrammer231

Reputation: 21

Adding data into arrayList of another class

I am just trying to be a little more familiar with arrayList and made a test program. I just want to add data into an arrayList of another class. It says that "The method add(arrayList) in the type Test is not applicable for the arguments (String)"

 package arrayList;

import java.util.ArrayList;
import java.util.List;

public class arrayList 
{

    public static void main(String[] args) throws Exception
    {
    ArrayList<String> cityList = new ArrayList<String>();
    // Add some cities in the list

    Test add = new Test();

    add.add("Dallas");

    System.out.print(cityList);
}
}

Here is the class that adds data into the arrayList package arrayList;

import java.util.ArrayList;
import java.util.List;

public class Test 
{
    public final ArrayList<arrayList> floors = new ArrayList<>();

    public void add(arrayList cityName)
    {
    floors.add(cityName);
    }
}

Upvotes: 1

Views: 3692

Answers (1)

Nicolas Filotto
Nicolas Filotto

Reputation: 44965

"The method add(arrayList) in the type Test is not applicable for the arguments (String)"

Simply because you try to add a String to an ArrayList<arrayList> while only objects of type arrayList are expected.

Change your code as next to be able to add String to your list:

// My list of String
private final List<String> floors = new ArrayList<>();

public void add(String cityName) {
    // Add a String to my list of String
    floors.add(cityName);
}

If you want to access to your list from outside the class, you could add a getter to your class Test, like this:

public List<String> getFloors() {
    return floors;
}

If you want to initialize your list from a list created outside your class, you could add a constructor to your class Test, like this:

private final List<String> floors;

public Test(List<String> floors) {
    this.floors = floors;
}

NB: As you are a beginner I provided a simple answer but please note that it is not a good practice to use directly a list coming from outside your class like in the constructor above or returning directly your list like in the getter above. A good practice would be to protect your list from outside classes to prevent bugs by making a copy of the provided list in case of the constructor and by returning a copy of your list or the unmodifiable version of your list in case of a getter.

Upvotes: 1

Related Questions