I've been trying to search, but I can't quite find the answer to my problem. I feel like I've implemented my generic datatype correctly but I'm still getting an error.
I'm doing an exercise where I'm given constructors/methods and variables (so I can't change the variable inputs for instance), and now I have to write the constructors/methods to make them work. The program creates an array (objects) that can grow by adding elements to it, and the comments above each method in the code explains what they do.
When I try to create the arrays in my two constructors, I get the error "Variable must provide either dimension expressions or an array initializer" for the empty array and "Type mismatch: cannot convert from T[] to int".
In my "add" method I get the error "Cannot invoke add(int, T) on the array type T[]" and finally in my "toArray" method I get the error "Type mismatch: cannot convert from Object[] to T[]".
The common theme seems to be that I haven't implemented the generic datatype correctly, but no matter how many times I try to search for similar questions, I can't see how what I've done have been different.
When searching, I see many people say that an array can't "grow" and to instead use an ArrayList, however there has to be a way to solve this with just an array, otherwise you can't solve this exercise.
import java.util.ArrayList;
import java.util.Arrays;
public class GrowingArray<T> {
private Object[] objects;
private int pointer;
//empty array
public GrowingArray() {
objects = new Object[];
}
//array that contains ds
public GrowingArray(T[] ds) {
objects = new Object[ds];
}
// add element e and return true
public boolean add(T e) {
pointer = 0;
objects.add(pointer++, e);
return true;
}
// return true if value d is found in the array
public boolean contains(T d) {
for(int i = 0; i <= objects.length; i++) {
if(objects[i] == d) {
}
}
return true;
}
// return the element on index i
public T get(int index) {
int i = index;
return objects[i];
}
// return first index containing d, if not found return -1
public int indexOf(T d) {
for(int i = 0; i <= objects.length; i++) {
if(d == objects[i]) {
return i;
}
}
return -1;
}
// return last index containing d, if not found return -1
public int lastIndexOf(T d) {
for(int i = objects.length; i >= 0; i--) {
if(d == objects[i]) {
return i;
}
}
return -1;
}
// return length of array
public int size() {
return objects.length;
}
// return a trimmed version of the array
public T[] toArray() {
return Arrays.copyOf(objects, objects.length);
}
}