Java sharing same values in a class

会有一股神秘感。 提交于 2021-02-05 12:32:06

问题


I have a class called Hand and another class to test it. Hand uses global variables and change their values with some methods if in class test I create two variables of the Hand class changes in one of the variables will affect the other. How can I make them separate ?

Class Hand:

private static List<Card> hand = new ArrayList<Card>();

Class Test:

        Hand hand1 = new Hand();
        Hand hand2 = new Hand();

If I add values to hand1 arraylist it changes also the values of hand2 arraylist. Can I separate them?


回答1:


Turn the private static List<Card> into a private List<Card>.




回答2:


Make private List<Card> hand = new ArrayList<Card>(); as instance variable rather then make it static..
Coz static is property of class and instance variables are property of Object... which is different for different Object ..but in case of static they are same for all objects..




回答3:


Remove the static modifier which is common for all instance of the class loaded in a particular class loader.




回答4:


The static keyword makes the variable class-scoped, not instance-scoped. That means the same value is common for all instances of the class. A non-static member is particular to every instance of the class. Remove the static keyword and you will get the desired behavior.



来源:https://stackoverflow.com/questions/7925447/java-sharing-same-values-in-a-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!