ArrayList automatically adding null items

前端 未结 2 1485
梦毁少年i
梦毁少年i 2021-01-18 09:45

Hello everyone. I\'m making a vocabulary App, in which I need to create a List (or ArrayList). To do so, I\'ve created the following piece

相关标签:
2条回答
  • 2021-01-18 09:46

    You're probably looking at its internal array with the debugger. That doesn't matter; it's just an implementation detail.

    What matters is what's visible through its public API. In other words, what calls to size() (and so on) tell you. (And if that doesn't return 1 in your code example, then something weird is going on!)

    0 讨论(0)
  • 2021-01-18 09:52

    From your screenshot it is clear that what is exactly

    [abc123, null, null, null, null, null, null, null, null, null, null, null]
    

    is not the ArrayList itself but its member variable objectData which happens to be the internal buffer of the ArrayList (where it actually stores elements you add to it).

    This buffer has a greater size than the actual size of the ArrayList because otherwise, every time that you add a new element, the whole objectData should be reallocated as a larger array and all elements copied, but this is surely expensive.

    Follow Oli's advice, just ignore the implementation details and trust only the interface.

    0 讨论(0)
提交回复
热议问题