I am studying generics now and I wonder how to build a parametrized class that can store some data for me. I want to know because of c++ influence on me. Secondly, I wonder how ArrayList is built.
My problem is you cannot make new instance of a class that has no default constructor, i.e. Integer. I know I should specialize my class in order to handle these classes individually. However, there is no specialization in Java as in c++.
How can I alter the code
import java.lang.*;
class test {}
class generic<T> {
private Class<T> type;
T element;
generic(Class<T> type) {
this.type = type;
try {
element = type.newInstance();
} catch (Exception e) {
System.out.println("error " + e);
}
}
static <T> generic<T> create(Class<T> type) {
return new generic<T>(type);
}
}
public class Generic {
public static void main(String[] args) {
generic<Test> test = generic.create(Test.class);
System.out.println(test);
}
}
so that it handles Integer instead of Test?
My reaction to your class is it attempting to do two things. Create the data and store the data. As you have discovered with your experience with the Integer class, there are many classes in Java that do not expose a public constructor let alone the default constructor. So there is no single way to create object instances that can be relied on for all possible types you will encounter. You state that your requirement is to store data so let’s remove the responsibility of creating data:
As for wondering how
ArrayListis built, Java is open source so you’re free to inspect how all the SDK types are implemented.