我有一个叫做 Hand 的类,还有另一个要测试它的类. Hand 使用全局变量并通过某些方法更改其值如果在类测试中,我创建了 Hand 类的两个变量其中一个变量的更改将影响另一个变量.我怎样才能将它们分开?
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>();类 Test :
Hand hand1 = new Hand(); Hand hand2 = new Hand();如果我将值添加到 hand1 数组列表中,它也会更改 hand2 数组列表的值.我可以分开吗?
If I add values to hand1 arraylist it changes also the values of hand2 arraylist. Can I separate them?
推荐答案设置私有列表< Card>hand = new ArrayList< Card>(); 作为实例变量,而不是使其变为静态..静态是类的属性,实例变量是对象的属性...对于不同的对象..是不同的.但是在静态的情况下,所有对象都相同.
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..
更多推荐
Java在类中共享相同的值
发布评论