Java find last member in index of array

前端 未结 2 1386
耶瑟儿~
耶瑟儿~ 2021-01-27 03:51

So let say I have an array of size 10 with index range from 0 to 9. I add a bunch of elements in and stop adding at index 6. So with array.length, I can know that the size of th

2条回答
  •  无人共我
    2021-01-27 04:03

    Since this is you assignment a trick is to add a variable to follow the number of elements added.

    So you can have a public int size = 0 variable and change you add and remove operations to increase and decrease this variable whenever you add or remove an element.

    Then in you add method you can have a simple check to see if you need to expand the array

    if (size == array.length)
       expandArray
    

提交回复
热议问题