Win a copy of Penetration Testing Basics this week in the Security forum!

# which one is better ....

ankur rathi
Ranch Hand
Posts: 3830
Suppose I have a list of some element and I want to retrieve the elements . So which option is much efficient and good out of this two & why ?

thanks a lot .

Mark Spritzler
ranger
Sheriff
Posts: 17278
6
Iterator is cleaner and easier to read.

Mark

Bilal Al-Sallakh
Greenhorn
Posts: 20
If you are using an ArrayList, it doesn't matter.
If you are using a LinkList, the Iterator is clearly more effecient.

ankur rathi
Ranch Hand
Posts: 3830
Why so ?

Steven Bell
Ranch Hand
Posts: 1071
On an ArrayList calling .get(int) is basically an index operation.
On a LinkedList calling .get(int) causes you to walk down the List starting at the first node until you get the the correct index. So you go from a O(1) operation to a O(n^2) operation. was trying to superscript the 2, didn't work

[ February 03, 2005: Message edited by: Steven Bell ]
[ February 03, 2005: Message edited by: Steven Bell ]

Sergey Sytnik
Greenhorn
Posts: 1
With Tiger u can use smth. like this:

or even better:

Ranch Hand
Posts: 57
the best way of itreating the elements in Collection
-------------------------
Collection list = new ArrayList();

Iterator listItr = list.iterator();
int size = list.size();
for(int i = 0;i<size;i++)
{
listItr.next();
}

ankur rathi
Ranch Hand
Posts: 3830
why so ???

Bilal Al-Sallakh
Greenhorn
Posts: 20
Originally posted by Steven Bell:
So you go from a O(1) operation to a O(n^2) operation.

I think you he goes from an O(1) operation to an O(n) one.

Bilal Al-Sallakh
Greenhorn
Posts: 20
Originally posted by Steven Bell:
So you go from a O(1) operation to a O(n^2) operation.

I think he goes from an O(1) operation to an O(n) one.

Bilal Al-Sallakh
Greenhorn
Posts: 20
Originally posted by rathi ji:
why so ???

You may find a solid data-structures foundation in many data-structures and algorithms book. I think a good java programmer should already be familiar with them.

Bilal Al-Sallakh
Greenhorn
Posts: 20
Originally posted by rathi ji:
why so ???

You may find a solid data-structures foundation in many data-structures and algorithms book. I think a good java programmer should already be familiar with them.

ankur rathi
Ranch Hand
Posts: 3830
the best way of itreating the elements in Collection
-------------------------
Collection list = new ArrayList();

Iterator listItr = list.iterator();
int size = list.size();
for(int i = 0;i<size;i++)
{
listItr.next();
}

why this is best ???
I think this is increasing line of code .
thanks .