Daniele Daniele - 5 months ago 11
Java Question

Most efficient way of creating a List for an Android App

As of in the title, I am experimenting with two different ways of creating an

ArrayListView
in android.

The first one looks like this:

list.add(new Obj("smth", "Note: na, na, na", image[0]));
list.add(new Obj("smth", "Note: na, na, na", image[1]));
list.add(new Obj("smth", "Note: na, na, na", image[2]));


and has a support Array for the images:

private int[] images = {
R.drawable.image1,
R.drawable.image2,
R.drawable.image3,
...}


the other way uses the getter and setter methods of the Obj.class. like this:

ArrayList<Obj> objects = new ArrayList<>();

Obj a=new Obj();
a.setName("smth");
a.setNote("na,na,na");
a.setImage(R.drawable.image1);
objects.add(a);

a=new Obj();
a.setName("smth");
a.setNote("na, na, na");
a.setImage(R.drawable.image2);
objects.add(a);

a=new Obj();
a.setName("smth");
a.setNote("na,na,na");
a.setImage(R.drawable.image3);
objects.add(a);


Is one of them better than the other? maybe it increases performance in some way? what if this list will be crowded with hundreds of Objects?

UPDATE:
I have tried to run an App with many Objects in the List and performance seems slightly better using the second method. But I'm sure there are even better ones!

Answer

Your second approach is better in terms of memory use. To condense the code you could do the following. Will give the same performance with lesser amount of code/ Probably also increase a bit of the performance because you are not calling so many setters with this.

ArrayList<Obj> objects = new ArrayList<>();

Obj a=new Obj("smth", "Note: na, na, na", R.drawable.image1);
objects.add(a);
a=new Obj("smth", "Note: na, na, na", R.drawable.image2);
objects.add(a);
a=new Obj("smth", "Note: na, na, na", R.drawable.image3);
objects.add(a);

And if you have a pattern for the values you put in the constructor, you could consider looping over and going about reassigning and adding.