-3

Just wondering how to add another object to a fixed object array.Would you change the length of the array?

object length is 43

for(int i=0;i<count;i++){
 object[count] =new Movie(movieID,movieTitle,Director,Writer,Duration,Genre,Classification,releaseDate,Rating);
}

this was the loop to create the first array of objects with a length of 43 How would you use a separate method to add another object to this array without using an array list?

alex
  • 74
  • 1
  • 8

2 Answers2

1

You would definitely need to reassign the original array, as arrays do have a fixed size. This tiny example does illustrate how it could be done.

public class A {
    private int i;

    public A(int i) {
        this.i = i;
    }

    public static void main(String[] args) {
        // Original array with the size 1;
        A[] arr = new A[1];
        // One default item
        arr[0] = new A(0);
        // Reassign array here, use a method returning a new instance of A[]
        arr = add(arr, new A(1));
        // just for printing.
        for(A a : arr) {
            System.out.println(a.i);
        }
    }

    public static A[] add(A[] inputArr, A newItem) {
        // The array will have another item, so original size + 1
        A[] buffer = new A[inputArr.length+1];
        // Copy the original array into the new array.
        System.arraycopy(inputArr, 0, buffer, 0, inputArr.length);
        // Add the new item at the end
        buffer[buffer.length-1] = newItem;
        // Return the "increased" array
        return buffer;
    }
}

The output now shows you have two items in the array.

O/P:

0
1

All in all it would be better to use a List here, but as you don´t want it i hope that this example can guide you to a way of doing it with arrays.

SomeJavaGuy
  • 7,307
  • 2
  • 21
  • 33
0

you can simple send the reference of the array to a method, then create a new array with size+1 , fill the array and return it, though this is a bad practice , if you need dynamic size just use arraylist

Amer Qarabsa
  • 6,412
  • 3
  • 20
  • 43