java - Null pointer exception populating a new array -
this question has answer here:
- what nullpointerexception, , how fix it? 12 answers
 
i trying implement vector of generic data type type taken input user such :
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 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 above code following output:
    enter data type of vector : integer exception in thread "main" java.lang.nullpointerexception     @ com.example.genericvector.genericvector.<init>(genericvector.java:12)     @ com.example.genericvector.genericvector.main(genericvector.java:40)     @ sun.reflect.nativemethodaccessorimpl.invoke0(native method)     @ sun.reflect.nativemethodaccessorimpl.invoke(nativemethodaccessorimpl.java:62)     @ sun.reflect.delegatingmethodaccessorimpl.invoke(delegatingmethodaccessorimpl.java:43)     @ java.lang.reflect.method.invoke(method.java:498)     @ com.intellij.rt.execution.application.appmain.main(appmain.java:147)  process finished exit code 1   i pretty new java, appreciated.
private generic_type [] vector;   only declares field (array) of generic type. initially, array null.
something like
private generic_type [] vector = new generic_type[10];   initializes field new vector (but please note individual array slots null @ point, too). but, uups, commentors right ... 1 of deficiencies of generics , arrays, can't use new[] generic types. on other hand, arrays have fixed size in java; have check if have grow/shrink underlying array! working solution be:
private list<t> vector = new arraylist<>();   for example (using existing java collection classes here).
final note: convention, generic types denoted using single upperchase characters. should genericvector<t> instead of generic_type.
Comments
Post a Comment