I have created my own data structure that functions similarly to an ArrayDeque and extends an AbstractList. The point of it is to hold other data structures, but not allow structures that have more than a specified number of elements.
For example (my constructor):
public MyD(Class<T> t, int limit)
{
}
Where limit determines the amount of elements allowed per data structure added to the ArrayDeque.
My issue is that, because I'm using generics, I don't technically know what type of data structure I'm working with at the time.
public void add(int i, T structure) {}
Where structure could be anything from an array, to ArrayList, to Queue, etc.
My question: Is there a way to take a generic value and generically cast it to get the amount of elements within if I know it will always be some form of data structure.
I have tried casting it to a simply array[], but if a List is passed through, it will break the functionality.
@SuppressWarnings({"unchecked"})
T[] array = (T[])x;
if(array.length > b) { return; }
You could use some reflection to test whether the passed structure is an array or a Collection and then get its size accordingly:
public void add(int i, T structure) {
int size;
if (structure.getClass().isArray()) {
size = Array.getLength(structure);
} else if (structure instanceof Collection) {
size = ((Collection) structure).size();
} else {
throw new IllegalArgumentException("Structure is neither an array nor a collection");
}
if (size > limit) {
return;
}
// ...
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments