Can any one tell me clearly why ?
Reading is simple in ArrayList,( we can access through its array index ), why not in linkedList
Inserting element in arrayList is tough i heard why ? easy in linkedList why ?
Deleting element in arraylist is tough why ? easy in linkedList why ?
I know some thing about arrays, but what going in linkedXXX
Thank you.
In an ArrayList, you keep an array of references in memory, that is to say, you have a memory position. When you ask for the first element of an ArrayList, you just access the memory position. When you access the 10th element, you access the memory position + 10 times the size of a reference.
In an LinkedList, you have one element, which has a reference to the next. The next one references the next, and so on. As you can see, there is no direct way of accessing the 10th element in a LinkedList without going one by one getting the next element.
So, your questions:
Inserting element in arrayList is touch i heard why ? easy in linkedList why ?
There are two problems with inserting an element into an ArrayList:
When you put an element in position 3, you need to first move every element starting at position 3 and shift them right once (3 becomes 4, 4 becomes 5, etc…) so that 3 becomes empty and you can put in your new element
If the array that backs your ArrayList is already full, you need to create a new one! This is very costly, since you need to allocate the memory again, and then copy all elements to the new array, and destroy the old one.
In a Linkedlist, on the other hand, you go to element 1, which points to 2, and then go to 2. In 2, there’s a reference to the old element 3, which you temporarily store elsewhere. You replace it with a reference to your new element, and in your new element, you make next point to the old 3. This is therefore way less costly.
Deleting element in arraylist is touch why ? easy in linkedList why ?
Similar reasons as inserting. In an ArrayList, you have to shift all the elements down again, in the LinkedList, once you are at element 2, you make its next point to 4, and voila, 3 is erased.
And for completeness
ArrayLists are great if you are going to access elements in a random order, but have the problems of adding and substracting. LinkedLists are great to add and remove, but getting an element that’s not the first or last takes extra cost. So there’s always a trade-off!