2017-05-11 124 views
1

书写方法在[位置]变量中存储的位置将[]插入到数字[]中。将数组插入另一个数组

public boolean insertArray(int location, double a[]) 
    {  
     if (length != MAX_CAPACITY) 
     { 
      numbers[location] = a[]; 
      length++; 
      return true; 
     } 
     return false; 
    } 

是否可以通过数组?

+1

“数字”的类型是什么? – shmosel

+0

使用循环。你可以使用'arraycopy',但我想这只是练习目的。 – Yoda

+0

当我们不知道问题的参数时,怎么会有这么多的答案? – shmosel

回答

4

您可以使用System.arraycopy

public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length) 

下面是一个简单的例子,你可以按照解决您的问题:

double a[] = {1, 2, 3, 4, 5}; 
double b[] = {6, 7, 8}; 
int local = 5; 
double result[] = new double[a.length + b.length]; 

System.arraycopy(a, 0, result, 0, a.length); 
System.arraycopy(b, 0, result, local, b.length); 
System.out.println(Arrays.toString(result)); 

输出

[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0] 
+0

这只将一个数组的内容复制到另一个(合并)...我相信问题是如何将一个数组(即对数组的引用)插入到另一个数组的特定位置(即两维数组) –

+0

@CarlitosWay所以你做出了反对票?你可以用'System.arraycopy'来做很多事情来检查我的例子 –

1

是否存在使用数组而不是列表的特定原因,如 作为ArrayList?

如果您使用java.util.List,则使用​​。

如果您使用的是数组,那么您需要执行数组分配和自我复制。下面是ArrayList.addAll(int, Collection)从OpenJDK的一个example implementation

// Copyright 1997-2007 Sun Microsystems, Inc. 
public boolean addAll(int index, Collection<? extends E> c) { 
    rangeCheckForAdd(index); 

    Object[] a = c.toArray(); 
    int numNew = a.length; 
    ensureCapacity(size + numNew); // Increments modCount 

    int numMoved = size - index; 
    if (numMoved > 0) 
     System.arraycopy(elementData, index, elementData, index + numNew, 
         numMoved); 

    System.arraycopy(a, 0, elementData, index, numNew); 
    size += numNew; 
    return numNew != 0; 
} 
1

您可以利用阵列了。

int[] numbers = ... 
int[] a = ... 

int n = numbers.length; 
numbers = Arrays.copyOf(numbers, numbers.length + a.length); 
System.arraycopy(a, 0, numbers, n, a.length); 

一般而言,List和ArrayList是更好的抽象,效率几乎相同。

1

是的,你可以。

但是阵列必须是二维Array!例如:

public static double[][] numbers = new double[MAX_CAPACITY][]; 

public boolean insertArray(int location, double[] a) 
{  
    if (length != MAX_CAPACITY) 
    { 
     numbers[location] = a; 
     length++; 
     return true; 
    } 
    return false; 
}