I've to solve a problem regarding generics which gives me quite the stomache ache.
Basically it's supposed to be an implementation for an array-based max-heap and I have to follow the given conditions. The code to start from looks like this:
//Interface with methods such as insert(), remove(), etc
public interface IMaxHeap> {
...
}
public class MaxHeap> implements IMaxHeap{
T[] m_array;
...
public MaxHeap(int size){
//TODO:
//m_array = new T[size];
}
public MaxHeap(T[] array){
//TODO:
//Deep copy of array into m_array
}
}
The code for the two constructors is what I'm strugling with. I am not supposed to modify the signature of the methods so I can't do things like this:
public MaxHeap(Class clazz, int size){
m_array = (T[]) Array.newInstance(clazz, size);
}
Additionally, doing the "unsafe" type-casting of an Object[] array like this gives me a runtime excetion (InvocationTargetException)
public MaxHeap(Class clazz, int size){
m_array = (T[]) new Object[size];
}
I've found a generic way to make a copy of my array, however it's not a deep copy:
public MaxHeap(T[] array){
m_array = Arrays.copyOf(array, array.length);
}
So that this point m_array[0] == array[0] which isn't what I'm looking for.
I'm also not supposed to add other constraints to the class (so no T exdends Cloneable either). Given these problems I haven't actually found a way to instantiate my arrays.
I'm somewhat new to generics (I've only been working with C++ templates) so those quirks with T are pretty annoying. Can you guys point me to a solution that works?
JavaScript questions and answers, JavaScript questions pdf, JavaScript question bank, JavaScript questions and answers pdf, mcq on JavaScript pdf, JavaScript questions and solutions, JavaScript mcq Test , Interview JavaScript questions, JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)