In this excercise I encountered the following:
public static void get10000(List list) {
if (list.isEmpty()) return;
int x = list.size() / 2;//. =====> why is de list.size divided by two?
for (int i = 0; i < 10000; i++) {
list.get(x); =====> why not list.get(i) ??
Why is the size divided in 2?
Resolved
Comments (2)
- Popular
- New
- Old
You must be signed in to leave a comment
Jakub Góźdź
14 February 2020, 14:14
Clean code:
This method just iterates through the entire list and perform get method on each iterate to simulate 10000 get operations.
They divide the size of the list by two because they want to get variable from the middle of the list. If they would choose the first element there would be no difference in delay between ArrayList and LinkedList.
LinkedList has low performance in case of get method. Because LinkedList to determine the address of the element has to get all earlier elements. From the first element, LinkedLink gets an address to the second element, from the second element get the address to the third one and so on. So, if the element that you want to get from LinkedList is far away from the beginning of the list it would take a long time to figure out where it is in the memory. But if you would to get first element it would take the same amount of time as for ArrayList. That's why they choose element in the middle.
Please look at the explanation here: https://codegym.cc/quests/lectures/questsyntax.level08.lecture05
+8
Misiu
14 February 2020, 13:54useful
Perhaps it means - get any, but the same element, eg. the middle one.
+1