Why use parallel arrays in Java?

前端 未结 4 1892
耶瑟儿~
耶瑟儿~ 2021-01-12 23:57

Is there any real use case for parallel arrays in Java? It seems too cumbersome to maintain N arrays which are interrelated.

Example:

int  ages[]   =         


        
4条回答
  •  甜味超标
    2021-01-13 00:32

    The only real advantage of parallel arrays in Java is as an (IMO extreme) measure to reduce object allocation and / or heap usage. For a large enough collection of objects, 3 arrays will occupy less space AND use fewer objects than a single array of instances of some custom class.

    This approach is normally a bad idea, since it makes your code a lot more fragile. Creating and using a custom class is the best approach in most situations.

    Note: the Performance Tips for Android advise otherwise, but those tips are primarily focused on reducing the frequency / impact of GC pauses on user experience. And even that advice is caveated in a couple of ways.

提交回复
热议问题