Java在类中共享相同的值 [英] Java sharing same values in a class

查看:29
本文介绍了Java在类中共享相同的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个叫做 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在类中共享相同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆