I need to be able to understand which method (listed below) would be more beneficial to use in a Java environment.
My problem is thus: I am creating a class in which I am going to use for holding multiple objects of the same type, however if I want to use it in the future, I want to be able to pass different objects to a different instance of Array2D. Its name is Array2D and contains private instance variables named rows
and columns
. However, what I want to do is be able to pass any object (when you instantiate it) to this class and be able to return the same type with methods inside of Array2D.
Method 1
Create Array2D using generic types. https://docs.oracle.com/javase/tutorial/java/generics/types.html
Method 2
Create a superclass that can be extended from to pass straight into Array2D.
Example of Method 1:
public class Array2D<T> {
private int rows;
private int columns;
private T[] t;
public Array2D(int rows, int columns) {
this.rows = rows;
this.columns = columns;
}
public T[] returnSomething() {
return t;
}
}
Example of Method 2:
Arrayable.java
public class Arrayable {
//all of my variables for arrayable class
}
Example.java
public class Example extends Arrayable {
//more stuff
}
Array2D.java
public class Array2D {
private int rows;
private int columns;
private Arrayable[] arrayable;
public Array2D(Arrayable[] arr) {
this.arrayable = arr;
}
public Arrayable[] returnSomething() {
return arrayable;
}
}
Main.java
public class Main {
public static void main(String args[]) {
Example ex1 = new Example();
Example ex2 = new Example();
Example[] ex3;
ex3[0] = ex1;
ex3[1] = ex2;
Array2D a2d = new Array2D(ex3);
Example[] finish = a2d.returnSomething();
}
}
The only problem I see with Method 2 is that for any class you want to give to Array2D, it has to extend Arrayable. Oh, and the fact that it takes double the time to do. Input??
If Method 1 is the way to go in this situation, please provide an example. I'm basically new to generic classes and setting them up. Thank you!
From what I understood, you want it to be generic for all types of objects, but when you instantiate it, it should only accept subclasses of the declared type. If this is the case, use generics. After you instantiate it, it will automatically accept subclasses of the defined type.
Basically, use your first method. Then change your main
like this:
public class Main {
public static void main(String args[]) {
Arrayable[] classArray = {
new SubClass1(),
new SubClass2()
};
Array2D<Arrayable> a2d = new Array2D<>(classArray);
Arrayable[] array = a2d.returnSomething();
}
}