【问题标题】:Static variables strange behavior in android [closed]静态变量在android中的奇怪行为[关闭]
【发布时间】:2013-04-06 18:41:19
【问题描述】:

我遇到了一个问题,很奇怪的问题。

当我更新类中的任何一个静态变量时,类中的其他静态变量也会更新,不知道为什么会这样。

请帮帮我,我什至不知道如何处理这个问题。

这条线产生了问题。

private static cSet currentSet = new cSet();
private static cSet currentPracticeSet = new cSet();
    public static void setCurrentPracticeSetRange(int from, int to)
{
    Log.e(currentPracticeSet.getCards().size()+" And "+currentSet.getCards().size(), to+" and "+from);
    getCurrentPracticeSet().getCards().clear();
    getCurrentPracticeSet().getCards().addAll(getCurrentSet().getCards().subList(from, to));

    Log.e("Range",currentSet.getCards().size()+"");
}

currentSet 和 CurrentPracticeSet 是类的私有静态成员。 谢谢,

【问题讨论】:

  • 这就是static 的意思。
  • 这样更好,但我们仍然需要查看您的static 变量声明。
  • 是的,我不知道。如果我猜我会说您在代码中的某处将currentSet 设置为currentPracticeSet(反之亦然)。如果你这样做,这两个变量现在指向同一个集合。
  • @RobertHarvey 为什么它们指向同一个集合,集合只是我定义的一个类。

标签: android static


【解决方案1】:

静态意味着变量的范围受类的限制,而不是对象。如果你改变一个值,它们都会改变。

阅读here了解更多信息。

【讨论】:

  • static 表示变量的作用域是类定义。这并不是一个真正的“实例”。
  • @RobertHarvey 我知道为什么我使用它们的静态。但这很奇怪,你在一个类中有 2 个静态变量,当你改变一个变量时,另一个变量也会更新。
  • @AhmadRaza:向我们展示包含变量声明的代码。我的猜测是你的代码中有一个错误,错误地设置了两个变量。
  • @AhmadRaza:您还没有向我们展示您的静态变量。我们需要看到这些。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-08-06
  • 2023-03-18
  • 1970-01-01
  • 1970-01-01
  • 2016-05-16
  • 2012-07-01
相关资源
最近更新 更多