
Question:
Writing method to insert a[] into numbers[] at a position stored in variable "location".
public boolean insertArray(int location, double a[])
{
if (length != MAX_CAPACITY)
{
numbers[location] = a[];
length++;
return true;
}
return false;
}
Is it possible to pass through an array?
Answer1:You can use <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/System.html#arraycopy(java.lang.Object,%20int,%20java.lang.Object,%20int,%20int)" rel="nofollow">System.arraycopy
</a> :
public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
<hr />Here is a simple example you can follow to solve your problem :
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));
<strong>Output</strong>
[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0]
Answer2:<strong>Yes, you can.</strong>
But the Array has to be a Two dimensions Array
! Example:
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;
}
Answer3:You can utilise Arrays too.
int[] numbers = ...
int[] a = ...
int n = numbers.length;
numbers = Arrays.copyOf(numbers, numbers.length + a.length);
System.arraycopy(a, 0, numbers, n, a.length);
In general List and ArrayList are better abstractions with almost the same efficiency.
Answer4:<blockquote>
Is there a specific reason you're using arrays instead of a List, such as an ArrayList?
</blockquote>If you're using a java.util.List, then use <a href="https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#addAll%28int,%20java.util.Collection%29" rel="nofollow">List.addAll(int location, Collection a)
</a>.
If you're using arrays, then you'll need to perform the array allocation and copying yourself. Here's an <a href="http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/ArrayList.java#ArrayList.addAll%28int%2Cjava.util.Collection%29" rel="nofollow">example implementation</a> of ArrayList.addAll(int, Collection)
from OpenJDK:
// 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;
}