棉绒警告:变量已分配给该值

时间:2019-01-21 17:59:55

标签: android android-studio warnings lint

我收到了棉绒警告

  

变量已分配给该值

在执行以下操作时

String[] sa =getStringArray();
sa = modifyArrayandMakeAwesomer(sa);  //get the warning here

似乎是对我的新警告。也许我的皮棉设置已更改。该代码按预期工作,没有任何错误。这是不好的做法吗?我应该声明第二个字符串数组吗?

2 个答案:

答案 0 :(得分:2)

好吧,您的代码可能令人困惑。这就是为什么您收到此警告。

您可以在“文件|设置|编辑器|检查| Java-声明冗余”中禁用“变量已分配给自身”检查。

答案 1 :(得分:2)

因为modifyArrayandMakeAwesomer(sa)正在使用其引用修改数据,

class Person {
   String name;
}

// this method just return the string value after making it uppercase,
public static Person modifyReference(Person p)
{
  p.name = "Gaurav";
  return p; // we don't need to return this from here since we are modifying directly to the reference.
}

public static int main(String[] args)
{
  Person p = new Person();
  p.name = "Max";
  System.out.println(p.name);
  modifyReference(p); // this is what you should do,
  p = modifyReference(p); // this is useless, since you have passed the reference of Person class 
  System.out.println(p.name);
}