Java在类中共享相同的值

编程入门 行业动态 更新时间:2024-10-10 19:19:19
本文介绍了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在类中共享相同的值

本文发布于:2023-11-28 08:54:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1641751.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类中   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!