【问题标题】:The user-supplied array is stored directly用户提供的数组直接存储
【发布时间】:2014-06-21 16:06:08
【问题描述】:

我已推荐:Security - Array is stored directly

我的代码是

public IndexBlockAdapter(String[] itemStr) {
    if(itemStr == null) { 
        this.itemStr = new String[0]; 
    } else { 
        this.itemStr = Arrays.copyOf(itemStr, itemStr.length); 
    }
}

但 Sonar 仍然拿起它并抱怨“数组是直接存储的”,尽管制作了一个副本。我很困惑。

感谢任何帮助!

【问题讨论】:

    标签: java arrays sonarqube


    【解决方案1】:
    Arrays.copyOf does a shallow copy. 
    

    它只是复制引用而不是实际值。 下面的代码会打印出所有的true,这就证明了这一点

    String [] str1 = {"1","2","3"};
    
        String [] str2 = Arrays.copyOf(str1, str1.length);
        for (int i=0;i<str1.length;i++) {
            System.out.println(str1[i] == str2[i]);
    
        }
    

    相反,如果你使用下面的代码,你会做一个深拷贝,你应该很好

    String [] str3 = new String[str1.length];
    for (int i=0;i<str1.length;i++) {
        str3[i] = new String(str1[i]);
    }
    for (int i=0;i<str1.length;i++) {
        System.out.println(str1[i] == str3[i]);
    }
    

    【讨论】:

    • 虽然这可能是为什么复制机制被抱怨的原因,但浅复制仍然足够。请记住:字符串是不可变的
    • 谢谢!我觉得用System.arrayCopy()或者Object.clone()也可以做深拷贝,比较简单。 @Hirak
    • 最后,我发现真正的原因是参数名称不能与实例变量相同。当我将参数名称更改为itemArr时,警告消失了。
    【解决方案2】:

    这应该适合你

     public IndexBlockAdapter(String[] newItemStr) {
     if(newItemStr == null) { 
        this.itemStr = new String[0]; 
     } else { 
        this.itemStr = Arrays.copyOf(newItemStr, newItemStr.length); 
     }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-04
      • 2015-12-17
      • 2019-01-29
      • 2020-08-09
      • 1970-01-01
      • 2016-08-31
      • 2013-05-30
      • 1970-01-01
      相关资源
      最近更新 更多