0

In my Data Structures class I've been tasked with creating an ArrayList of generic objects of a given type. This is essentially a class that behaves like an array with some extra functionality attached. It looks something like this.

    public class GenericArray<T>
    {
        // The array
        private T[] array;
        private int size;

        // Constructor
        public GenericArray(int arrsize)
        {
            size = arrsize;
            array = new T[size + 1];
        }
        // Array methods
        public T getItem(int index)
        {
            return array[index];
        }
        public int getCount()
        {
            int count = 0;

            for(int i = 0; i < array.Length; ++i)
            {
                if(array[i] != null)
                    count++;
            }
            size = count;
            return count;
        }
    }

We're required to create the various methods by which you interact with the array. I'm having a particular problem when it comes to deleting items from the array. I have a deleteLast method which I assumed would simply set the last item to null, like so:

        public void deleteLast()
        {
            int i = this.getCount()-1;
            array[i] = null;
        }

However I am getting the error that I cannot convert the parameter to null, as T may not be a nullable value type, which makes sense. However, I don't know how to remove them otherwise. I can't find any useful information on this through Google, so I've come to Stack Overflow.

Any help is appreciated. Thanks :)

1 Answers1

0

Why don't you use List<T> instead of T[] ? That should easily solve all your problems! You haven't handled cases around array size changes (for growing and reducing array size), enumeration, etc. Ideally I would implement IEnumerable and implement rest of the functions!