Reputation: 19
I should write a method that returns all cousins of the Person as an array of Person objects. A Person object has mother, father, children[] etc. as its instance variables and I should use this method to find all siblings of a Person's uncles and aunts then their children.
public Person[] allSiblings(){
int a = this.mother.children.length - 1;
Person[] siblings = new Person[a];
for(i=0; i<siblings.length; i++){
if(this.mother.children[i] == this)
continue;
else{
siblings[i] = this.mother.children[i];
}
}
return siblings;
}
So how can I merge these children arrays and return as one Person array in allCousins()
method. I know it would be easier to use ArrayList but we are not allowed.
Thanks in advance.
Upvotes: 0
Views: 1550
Reputation: 2985
The link mentioned by JoshOvi is good one. If you want to create your own implementation, consider ArrayUtils as reference -
public Object[] mergeArray(final Object[] arr1, final Object[] arr2) {
if (arr1 == null) {
return clone(arr2);
}
else if (arr2 == null) {
return clone(arr1);
}
Object[] mergedArray = new Object[arr1.length+arr2.length];
System.arraycopy(arr1, 0, mergedArray, 0, arr1.length);
System.arraycopy(arr2, 0, mergedArray, arr1.length, arr2.length);
return mergedArray;
}
public Object[] clone(Object[] array) {
if (array == null) {
return null;
}
return (Object[]) array.clone();
}
Upvotes: 0
Reputation: 88
Have a look at How can I concatenate two arrays in Java? There are some methods on how to do that. The trick is to either use a ready made function (which you probably are not allowed if Lists are forbidden) or to create a new Array with the sum of the two original Arrays as length.
Upvotes: 1