有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java用户提供的数组直接存储

我提到: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); 
    }
}

但声纳仍然拿起它,并抱怨“阵列直接存储”,尽管制作了一个副本。我很困惑

感谢您的帮助


共 (2) 个答案

  1. # 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]);
    }
    
  2. # 2 楼答案

    这应该对你有用

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