0

I get this object reference not set to an instance of an object error when I call constructor for CircularList.

Element:

 class Element
{
    public Element next;
    public String data;
}

List:

class CircularList
    {
        public Element[] arr;

        public CircularList(int n) //capacity
        {
            arr = new Element[n];

            for (int i = 0; i < n; i++)
            {
                if(i==n-1) arr[i].next = arr[0];
                else
                arr[i].next = arr[i+1];

            }

        }
    }
wdc
  • 2,623
  • 1
  • 28
  • 41

1 Answers1

1

Your array isn't initialized:

  class CircularList
  {
      public Element[] arr;

      public CircularList(int n) //capacity
      {
          arr = new Element[n];

          for (int i = 0; i < n; i++)
              arr[i] = new Element();

          for (int i = 0; i < n; i++)
          {
              if(i==n-1) arr[i].next = arr[0];
              else
              arr[i].next = arr[i+1];

          }

      }
  }

this will make sure you have valid items in it.

InteXX
  • 6,135
  • 6
  • 43
  • 80
Noctis
  • 11,507
  • 3
  • 43
  • 82
  • Thanks, it does work now. But shouldn't `arr = new Element[n]` make an array of `Element` objects? Why should you initialize them each separately? – wdc Dec 25 '16 at 12:04
  • 2
    no, it doesn't initialize them. it's just allocates space for them. – Noctis Dec 25 '16 at 12:05