Question

I've seen several threads for sharing a variable between classes but I can't find one for methods. Is it possible?

For example, in method A, I read a csv file and put the contents into a list.

In method B, I want to sort the list created in method A. How can I use the list created in A?

Was it helpful?

Solution

You can either declare the list as a variable of the class (outside of your methods) so that it can be used throughout the class, or you an declare it within the A method and pass it to other methods as shown below:

public static void main(String[] args)
{
    A();
}

public static void A()
{
   ArrayList<String> stral = new ArrayList<String>();
   //fill ArrayList
   B(stral);
}

public static void B(ArrayList<String> al)
{
    //do whatever you want with al
}

Hope this helps!

OTHER TIPS

Variables declared inside a method are instance variables and their scope is only within the method itself. You can not access a variable declared inside one method from another.

However if you declare the List outside the method and inside the class itself you can either pass the List into both methods or access them as instance variables of the class. They will all be the same List since they are just different references to the same object.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top