简体   繁体   English

如何在方法之间共享变量?

[英]How to share a variable between methods?

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. 例如,在方法A中,我读取了一个csv文件并将其内容放入列表中。

In method B, I want to sort the list created in method A. How can I use the list created in A? 在方法B中,我想对在方法A中创建的列表进行排序。如何使用在方法A中创建的列表?

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. 但是,如果在方法外部和类本身内部声明List,则可以将List传递到两个方法中,也可以将其作为类的实例变量进行访问。 They will all be the same List since they are just different references to the same object. 它们都是相同的List,因为它们只是对同一对象的不同引用。

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: 您可以将列表声明为类的变量(在方法之外),以便可以在整个类中使用它,也可以在A方法中声明它,并将其传递给其他方法,如下所示:

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! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM