-6

I need to write a method ePlus that accepts the Employee2 array e as a parameter and returns an Employee array. The returned array should be one element larger than e and contain all elements of e in the same indexes. To expand e, use: e = ePlus(e);. This is what I have so far:

import java.util.Scanner;

public class MyClass {

    public static Employee2[] ePlus(final Employee2[] e) { 
        // Code in progress
        return new Employee[0];
    }

    public static void main(final String[] args) {
        Employee2[] e = new Employee2[0]; 
        int counter = 0; //int variable = counter
        Scanner scanner = new Scanner(System.in);

        e = ePlus(e);
        System.out.println(e);
    }
}

Thank you for the help!

Pedro Rodrigues
  • 1,662
  • 15
  • 19

4 Answers4

1
public Employee2[] ePlus(Employee2[] input) {
    Employee2[] output = new Employee2[input.length + 1];
    System.arraycopy(input, 0, output, 0, input.length);
    return output;
}
0

You have a number of options, perhaps the easiest being System.arraycopy() see How to copy an Array in Java

hoos
  • 174
  • 2
  • 10
0

An array is not mutable so you can probably use an arraylist and return it's conversion as an array( if needed ).

Neha
  • 3,456
  • 3
  • 14
  • 26
0

As suggested by @StephenC You can use Arrays.copyOf(T[] original, int newLength).

public Employee2[] expandOne(Employee2[] original) {
    int n = original.length;
    Employee2 [] expanded = Arrays.copyOf(original, n+1);

    expanded[n] = new Employee2(); // Assuming Employee2 has a default constructor.

    return expanded;
}
xiaofeng.li
  • 8,237
  • 2
  • 23
  • 30