1

I have a generic class

public class GenericBookDet<K,V>
{
   private K bkId;
   private V bkDescription;

   public GenericBookDet()
   {
     this.bkId = null;
     this.bkDescription = null;
   }

   public GenericBookDet(K bkId, V bkDescription)
   {
      this.bkId = bkId;
      this.bkDescription = bkDescription;
   }
   ...
   //getter methods
   //setter methods
}

I have created an array of this class in another class and want to add new books.

public class GenericBookStore<K,V> 
{
   static int noOfbooks = 0;
   GenericBookDet<K,V>bk1[];

   public int addBook(K key, V bkDescription)
   {
       this.bk1[noOfbooks] = new GenericBookDet<K, V>(key,bkDescription);
       this.bk1[noOfbooks].setbkDescription(bkDescription);

       ++noOfbooks;
       return noOfbooks;
   }
}

I am calling the addBook method in the following way :

GenericBookStore<String, String> bkStore = new GenericBookStore<String,String>();
bkStore.addBook("1010", "ABCD");

But this throws a NullPointerException at first line of the addBook method.

I want to create an generic book array in GenericBookStore to which I can pass String or and object in bkDescription field;

Neeraj
  • 48
  • 3
  • 9

2 Answers2

6

The NPE happens because you didn't initialize GenericBookDet<K,V>bk1[]

GenericBookDet<K,V>bk1[] = new GenericBookDet[10]

You cannot create arrays of parameterized types. You can add@SuppressWarnings("unchecked") so you don't get any warning.

Also noOfbooks shouldn't be static. If you have more than 10 elements you have to resize the array: create a new one and move everything in it.

The best option is to use a List<GenericBookDet<K,V>>.

user1121883
  • 5,153
  • 3
  • 30
  • 34
  • 3
    Note that you'll get type warnings. I think there is no good way to create a generic array. Consider using a List (especially since you seem to want to grow it). – Thilo Sep 05 '16 at 07:27
3

Thou shalt not create arrays of generic types; see oracle why that is; and what can happen when one does it nonetheless.

The correct answer is to use a List<GenericBookDet<K,V>> instead; and forget about using arrays here in the very first place; like

public class GenericBookStore<K,V> 
{
   private final List<GenericBookDet<K,V>> descriptions = new ArrayList<>;

  public int addBook(K key, V bkDescription) {
     descriptions.add(new GenericBookDet<>(key,bkDescription)));
     return descriptions.size();
  }

Especially, as your code is dynamically adding new books; whereas arrays have a fixed size. Yet another reason to simply use a List/ArrayList which allows you to grow dynamically!

If one absolutely wants to use generic arrays, better read this here, too.

Community
  • 1
  • 1
GhostCat
  • 127,190
  • 21
  • 146
  • 218