0

I am working on a project and I am stuck on this method public DynArray(boolean allowNulls).

I was wondering if anyone could help me with this method. What I have to do is create a DynArray object that may allow or disallow its elements to be null values, depending upon the value provided for the allowNulls parameter.

So far I have

 public class DynArray<T>  {     
   private static final int INITIAL_CAPACITY = 10;
   private T[] theData;
   private int size = 0;
   private int capacity = 0;

 public DynArray( boolean allowNulls ) {
   capacity = INITIAL_CAPACITY;

   if( allowNulls == true){
    // ???
   }
   else {
    // ???
   }
 }

 public DynArray() {
  capacity = INITIAL_CAPACITY;
  theData = (T[]) new Object[capacity];
 }

Can someone please point out where I am going wrong?

Rebse
  • 10,307
  • 2
  • 38
  • 66
  • Why isn't there an `allowNulls` instance variable in your class since this is an essential information for operation? – fge Feb 19 '14 at 22:23
  • It doesnt look like you allow the object to be constructed with the values. I assume you are going to be providing a .add(T) method. The allowNulls boolean you pass in the constructor should be stored as a instance variable, and you should check that value in your .add() method, so that users cannot add a null. – Mark W Feb 19 '14 at 22:24
  • possible duplicate of [How to: generic array creation](http://stackoverflow.com/questions/529085/how-to-generic-array-creation) – Luiggi Mendoza Feb 19 '14 at 22:25

1 Answers1

5

What you need to do is create a private boolean within your class to hold the value of allowNulls. Then, check this value within your insert/add methods.

Example:

private boolean allowNulls = false;

 public DynArray( boolean allowNulls ) {
       capacity = INITIAL_CAPACITY;
        this.allowNulls = allowNulls ;    
   }

public void addMethod(T element)
{
   if( allowNulls || null!=element) //cheaper to check allowNulls first
   {
        // Put insertion code here
   }
   else
      throw new InputMismatchException("DynArray not initialized to support null");

}
Menelaos
  • 23,508
  • 18
  • 90
  • 155