【问题标题】:Assigning all values to array on the whole [duplicate]将所有值分配给整个数组[重复]
【发布时间】:2016-08-19 08:18:31
【问题描述】:

我正在编写一个 Java 程序,我正在使用以下代码将一些变量分配给数组:

for(int j=1;j<P.maxNetworkPow;j++){
    node.succList[j]=node.succ.succList[j-1];
}

谁知道如何在没有for 循环的情况下将所有值分配给数组?

【问题讨论】:

  • 你可以使用 System.arraycopy System.arraycopy(node.succ.succList, 0, node.succList, 1, P.maxNetworkPow-1) 之类的东西
  • 我不明白人们如何认为这个问题是关于填充数组的,而 OP 显然想从一个数组复制到另一个数组

标签: java arrays


【解决方案1】:

使用Arrays.fill(node.succList, value)javadoc。 如果你想用一个值填充数组。

如果你想从另一个使用初始化数组

System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length)javadoc

【讨论】:

    【解决方案2】:

    使用 System.arraycopy。示例如下:

    import java.lang.*;
    
    public class SystemDemo {
    
       public static void main(String[] args) {
    
       int arr1[] = { 0, 1, 2, 3, 4, 5 };
       int arr2[] = { 5, 10, 20, 30, 40, 50 };
    
       // copies an array from the specified source array
       System.arraycopy(arr1, 0, arr2, 0, 1);
       System.out.print("array2 = ");
       System.out.print(arr2[0] + " ");
       System.out.print(arr2[1] + " ");
       System.out.print(arr2[2] + " ");
       System.out.print(arr2[3] + " ");
       System.out.print(arr2[4] + " ");
       }
    }
    

    将输出: 数组2 = 0 10 20 30 40

    【讨论】:

      【解决方案3】:

      正如用户 khelwood 指出的那样,您可以使用 System.arraycopy 将特定范围内的元素从一个数组复制到另一个数组。

      方法签名是:

      public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
      
      • src 是要复制的源数组
      • srcPos 是源数组中的起始位置
      • dest 是您要将数据复制到的目标数组
      • destPos 是目标数组中的起始位置
      • length 是复制的数组元素个数

      对于你的情况,它会是

      System.arraycopy(node.succ.succList, 0, node.succList, 1, P.maxNetworkPow - 1);
      

      这意味着将 node.succ.succList 的起始索引 0P.maxNetworkPow - 1 元素复制到数组 node.succList 的起始索引 1

      你必须小心,P.maxNetworkPow 不大于每个数组的长度,否则你会得到一个IndexOutOfBoundsException

      【讨论】:

        猜你喜欢
        • 2019-05-23
        • 1970-01-01
        • 1970-01-01
        • 2018-04-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-14
        • 2015-12-26
        相关资源
        最近更新 更多