✅ How can I check if an array need to be resize when adding an element
Hello guys, can someone suggest an idea of how to check whether the array is full and need to be resize when adding an element please. Since the array is a generic type and can have any data type, I can't check if the last index of the array contains a specific default value of a data type, like I can't assume it's an int and so have a default value of 0. Moreover, I don't think it would be right to assume 0 is a default value since our array can have a value of 0 as its element.
10 Replies
any reason why not just List<T> ?
to answer your question, to check if the array is full you must track it when they're added by increasing the count/length property, assuming you want to roll your own count/length mechanism
it was a class exercise, we don't have the flexibility :c
ohh okay I see, like, each time we want to add something, we would do: obj.Add(item)
now, if count not equal to size of array - 1, then array is not full, else, array is full, resize, use bigger size (double its size)
this to get you going
yep I see, thanks !!
by the way
count should be static, no?
like every element should share this variable when an item is added?
Unknown User•3w ago
Message Not Public
Sign In & Join Server To View
hmm in terms of a variable, I know that the variable is shared among all objects
in context of a method, we don't need an object to call a static method
if I remember correctly :c
well no, I think the way I think of it is wrong, I thought that we would create multiple objects then add item but this doesn't really make sense to add static here because an object can be half full and count can be at array.Length
yeah sorry my bad, I got the wrong reasoning
the idea is count should be unique to every object
please confirm if my statements were right :c in case I need to clear any confusion😭
your understanding of static is correct, and that u want the count to be unique to each instance of your list
Unknown User•3w ago
Message Not Public
Sign In & Join Server To View
BTW to "resize" an array you use
Array.Resize
which takes the array and the new size
Doesn't resize, but rather makes a new array. It's the correct way of resizing though
There's actually no such thing as resizing an arrayYeah, noted
Yep, I wrongly thought of it at first, but it s clear now, thanks !