문제

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?

도움이 되었습니까?

해결책

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!

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top