Java 在一个类中共享相同的值 [英] Java sharing same values in a class
问题描述
我有一个名为 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>();
类测试
:
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?
推荐答案
制作 private List
作为实例变量而不是使其成为静态..
因为静态是类的属性,实例变量是对象的属性......对于不同的对象是不同的......但是在静态的情况下它们对于所有对象都是相同的......
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 在一个类中共享相同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!