0

I want to create a class (Array) that performs different methods on arrays. What I have so far is overloaded constructors for different types of arrays (ints, strings, etc). However this class will also need to create an array of classes, so how could I pass in a class name and have my Array class create an array of that class?

I could just hard code it in for the class I know I will make an array of but I want to make my Array class versatile enough to have this work with any class I make in the future.

Ganlas
  • 51
  • 5
  • 2
    Maybe you're looking for [Array.newInstance](https://docs.oracle.com/javase/7/docs/api/java/lang/reflect/Array.html#newInstance(java.lang.Class,%20int...)) – aioobe Jul 29 '19 at 21:19
  • 1
    Possible duplicate of [How to create a generic array in Java?](https://stackoverflow.com/questions/529085/how-to-create-a-generic-array-in-java) – azurefrog Jul 29 '19 at 21:30

2 Answers2

3

You can do something like:

public class Array<T> {
    private final T[] arr;

    public Array(final int size, final Class<T> clazz) {
        this.arr = createArray(size, clazz);
    }

    private T[] createArray(final int size, final Class<T> clazz) {
        return (T[]) java.lang.reflect.Array.newInstance(clazz, size);
    }
}

which you can call instantiate by using:

final Array<String> strings = new Array<>(5, String.class);

I would also suggest a different name for your class as Array is already used by the Java API.

andresp
  • 1,507
  • 14
  • 29
  • 1
    What does the "T" mean? and would this code go inside my Array class? So when I instantiate the class in my code elsewhere I can pass in the type and size? Also why are you using the final keyword here? – Ganlas Jul 29 '19 at 21:24
  • 3
    T is a generic type. You can learn more about them here: https://docs.oracle.com/javase/tutorial/java/generics/types.html – andresp Jul 29 '19 at 21:26
  • 1
    I've adapted my example so it hopefully becomes clearer to you how you can use it in your class. The use of final is just a good practice when you don't need your variables or fields to be mutable. It would work even without final. – andresp Jul 29 '19 at 21:40
0

As @andresp said, you can make a new class with an array as a private field. Another option to avoid having to pass a Class<T> as an argument in addition to the type parameter is to replace the array with java.util.ArrayList, which functions just like an array with a few differences.

For example:

public class MyArray {
    private final java.util.ArrayList arr;
    public MyArray(java.util.ArrayList arr) {
        this.arr = arr;
    }

    // Add your additional methods here.
}
MAO3J1m0Op
  • 412
  • 3
  • 13