android - Java - best way to implement a dynamic-size array of objects -


i novice java.

i have implement array of objects changes in size during execution.

the code writing going ported on android, too.

according experience, what's best class implement that?

thanks,
dan

java has inadequate template capability. long want array of objects, arraylist<t> good. primitives, it's awful.

assuming have hierarchy of objects want put in list, arraylist ideal:

arraylist<vehicle> vehicles = new arraylist<vehicle>();  vehicles.add(new car(...)); vehicles.add(new truck(...)); 

i'm assuming in above example vehicle base class, , car , truck subclasses.

on other hand, if want list of numbers, java highly inefficient. each object reference (really 4 byte pointer) 12 byte chunk of memory, plus you're using. since arraylist cannot apply int, means creating list of numbers means:

  1. creating list of integer, object wrapper int.
  2. converting objects every time pull out number. done automatically these days, takes time.
  3. initializing 5 times storage needed.

so, if manipulating big chunks of primitive data (int, float, double) can worth while writing own version of arraylist. particularly important when data big , platform small (like handheld android thingy).

compare this:

arraylist<integer> list = new arraylist<integer>(); (int = 0; < 1000000; i++)   list.add(i): 

to:

public class intarray { private int[] data; private int used; private void grow() {  // implement code make data double in size here... } public intarray(int size) {   data = new int[size];   used = 0; }  public void add(int i) {   if (i >= data.length) grow();   data[used++] = i; } }  intarray list2 = new intarray(1000000); (int = 0; < 1000000; i++)   list2.add(i); 

the last time benchmarked it, optimal use of primitive list more 10 times faster admittedly suboptimal use of arraylist. more fair, pre-allocate arraylist right size -- it's still way slower.

linkedlist worthwhile if inserting in beginning or middle of list. if list being built adding end, arraylist thoroughly dominate linkedlist. typical list of objects building in order, arraylist looking for. big list of primitives int or double, write own list.


Comments

Popular posts from this blog

android - Spacing between the stars of a rating bar? -

aspxgridview - Devexpress grid - header filter does not work if column is initially hidden -

c# - How to execute a particular part of code asynchronously in a class -