2

I made this class ArrayBuilder with generics to make some basic operation to manage an array of T objects.

public class ArrayBuilder<T> {

@SuppressWarnings("unchecked")
public ArrayBuilder(Class<T> ct, int dim){
    container = (T []) Array.newInstance(ct, dim);
}

public T getElement(int index){
    return container[index];
}
public void setElement(int index, T value){
    container[index] = value; 
}
public T[] getContainer(){
    return container;
}

T[] container;

public static void main(String[] args) throws ClassNotFoundException {
    PrintStream ps = new PrintStream(System.out);
    Scanner sc = new Scanner(System.in);
    ps.print("che array desidera? ");
    String nameClass = "discover.";
    nameClass = nameClass + sc.nextLine();
    Class<?> toManipulate = Class.forName(nameClass);
    //Type type = toManipulate.getGenericSuperclass();
    ArrayBuilder<toManipulate> ab = new ArrayBuilder<toManipulate>(toManipulate, 10);

}

}

in main, program asks to the user to insert the name of the Class wich he prefers, so I want to use ArrayBuilder constructor to create this kind of array but compiler doesn't accept variable toManipulate in the angular brackets. Maybe Do I have to extract generic Type from the instance toManipulate?

1 Answer 1

1

Generics are a compile time feature. What you have can equally be handled by raw types as you don't know what the type is at compile time.

Class toManipulate = Class.forName(nameClass);
ArrayBuilder ab = new ArrayBuilder(toManipulate, 10);

or if you really want to use generics you can do

Class<?> toManipulate = Class.forName(nameClass);
ArrayBuilder<?> ab = new ArrayBuilder<Object>(toManipulate, 10);
Sign up to request clarification or add additional context in comments.

3 Comments

Or in this case an ArrayBuilder<Object> seems to be a better option. (No warning about raw types.)
@GáborBakos <Object> means it creates Object not a sub-class. ? extends Object or just <?> implies it creates an object which extends Object
I believe the second one requires a cast on toManipulate

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.