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 :)

2

1 Answer 1

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!

Sign up to request clarification or add additional context in comments.

4 Comments

That would defeat the purpose of learning how to implement the data structure.
In an array you don't actually delete an item. Instead you can set the array item to the default value for type T
I have actually handled cases around array resizing. I just haven't included it in my sample code as I felt it wasn't necessary to demonstrate the problem I was having.
Oh yes! You are right. I saw your comment now 👍🏻

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.