Reputation:
this is for a assignment, and one of the tasks is to create a abstraction of a array, does it mean that i am declaring a array that's abstract here, if so how would i declare it
private abstract Array<TYPE> Disk = new Array<TYPE>()
? something like that? or is it impossible to create a abstract array and its talking about making a class abstract and inserting a array in that class
// Build an abstraction of an array of integers on disk. If the file exists, * it should be opened and its length calculated (size parameter is ignored). * If the file doesn't exist, it should be created and size zeros should be * written to the file. ^^ goal here
please don't answer or give me any code, other than a yes or no to declaring that array and wether it would work
Upvotes: 3
Views: 218
Reputation: 9424
The given input is a bit sparse, so I can only guess what to do.
An abstraction can be interpreted in multiple ways.
or, as I would argue:
So In my opinion, you have to create a class having the asked operations, and implement some store/load methods, and return the appropriate results.
Upvotes: 2
Reputation: 7604
You can't have abstract fields like in your example.
About an abstraction over arrays - you might be able to do it, but I don't think it's worth it. List
s and other classes have their type parameters erased at runtime, so you can do all sorts of casting with them. However, arrays know the class of their elements, meaning you can't just do T[] foo = new T[]{}
given some type parameter T
. You could, of course, cast an Object[]
to a T[]
, but even if that works at compile time, you would get a ClassCastException
at runtime.
However, if you have a Class<T>
object in addition to some type parameter T
, you can use Array.newInstance()
to create arrays. Here's one way you could do it, but casting, say, a MyArray<String>
to a MyArray<Object>
, and then using getArray
as an Object[]
, will cause a class cast exception.
class MyArray<T> {
private final T[] arr;
public MyArray(Class<T> klass, int n) {
arr = (T[]) java.lang.reflect.Array.newInstance(klass, n);
}
public T get(int index) {
return (T) arr[index];
}
public void set(int index, T t) {
arr[index] = t;
}
}
Upvotes: 1