Cataclysm
Cataclysm

Reputation: 8548

Iterating reference Object List

Can anyone suggest me which option to choose and why ?

List<MyObject> list =  new ArrayList<MyObject>();
// insert some objects for it

1). for(int i = 0 ; i < list.size() ; i ++ ) {
       System.out.println(list.get(i).getAttribute1());
       System.out.println(list.get(i).getAttribute2());
    }

2). for(int i = 0 ; i < list.size() ; i ++ ) {
        MyObject obj = list.get(i);
        System.out.println(obj.getAttribute1());
        System.out.println(obj.getAttribute2());
    }

Yes , I know ... they will produce same results but I would like to know which option was more efficient , well-format , widely use and why ? I just notice only that first option will write more longer than another between them. Any suggestions ?

Upvotes: 0

Views: 52

Answers (1)

AJJ
AJJ

Reputation: 3628

Option: 1 Get is used twice on the list which is an additional process

Option: 2 Only one get is used which reduces the process. So this is better on compared to option:1

In both your options, the list.size() will be computed for each iteration of the for loop. To avoid this you can compute the length prior to iteration starts as,

for (int i = 0, length = list.size(); i < length; i ++) {
   // your code here

}

The efficient way is to use the for each loop as,

for (MyObject obj: list) {
  System.out.println(obj.getAttribute1);
}

Upvotes: 1

Related Questions