I am trying to implement a vector of generic data type where the type is taken as input from the user such as :
package com.example.genericvector;
import java.util.Scanner;
public class GenericVector <generic_type>{
private int length;
private generic_type [] vector;
GenericVector(generic_type element){
this.vector[0] = element;
}
public void allocate_size(int length){
}
public void push_back(generic_type element){
}
public void display(generic_type [] vector){
for(generic_type element : vector)
System.out.print(element);
System.out.println();
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the data type of vector : ");
String vector_type = scanner.next();
switch (vector_type){
case "integer":
GenericVector <Integer> vector_int = new GenericVector <Integer>(new Integer(10));
break;
case "double":
GenericVector <Double> vector_double = new GenericVector <Double>(new Double(10.57));
break;
default:
System.out.print("Invalid data type");
}
}
}
Upon running the above code I get the following as output:
Enter the data type of vector : integer
Exception in thread "main" java.lang.NullPointerException
at com.example.genericvector.GenericVector.<init>(GenericVector.java:12)
at com.example.genericvector.GenericVector.main(GenericVector.java:40)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Process finished with exit code 1
I am pretty new to Java, so any help will be much appreciated.