Adding basic Big O for ArrayList methods (#20859)
* Adding basic Big O for ArrayList methods I added average O(n) for basic methods in arraylist. This is important for every programmer to know. * minor edits * moved a few lines
This commit is contained in:
committed by
Christopher McCormack
parent
196a4f8233
commit
dac0ccfe2a
@ -79,10 +79,27 @@ Since ArrayList implements *List*, an ArrayList can be created using the followi
|
|||||||
```java
|
```java
|
||||||
Collections.reverseOrder());
|
Collections.reverseOrder());
|
||||||
```
|
```
|
||||||
|
|
||||||
An ArrayList allows us to randomly access elements. ArrayList is similar to *Vector* in a lot of ways. But it is faster than Vectors. The main thing to note is that - Vectors are faster than arrays but ArrayLists are not.
|
An ArrayList allows us to randomly access elements. ArrayList is similar to *Vector* in a lot of ways. But it is faster than Vectors. The main thing to note is that - Vectors are faster than arrays but ArrayLists are not.
|
||||||
|
|
||||||
So when it comes down to choosing between the two - if speed is critical then Vectors should be considered, otherwise ArrayLists are better when it comes to storing large number of elements and accessing them efficiently.
|
So when it comes down to choosing between the two - if speed is critical then Vectors should be considered, otherwise ArrayLists are better when it comes to storing large number of elements and accessing them efficiently.
|
||||||
|
|
||||||
|
## Basic Big O for ArrayList Methods:
|
||||||
|
|
||||||
|
`.get(int index)`
|
||||||
|
- O(1). This will always be constant time.
|
||||||
|
|
||||||
|
`.add(E ele)`
|
||||||
|
- O(1). We are only adding an element to the END of the list.
|
||||||
|
|
||||||
|
`.add(int ind, E ele)`
|
||||||
|
- O(n). Because of the way an ArrayList is implemented, we must do shifting which requires O(n) time on average.
|
||||||
|
|
||||||
|
`.remove(int ind)`
|
||||||
|
- O(n). For the same reason as above. The elements must be shifted after removal.
|
||||||
|
|
||||||
|
It is important to understand the Big O for methods of data structures. This way, you can choose the most efficient data structure for your program.
|
||||||
|
|
||||||
|
|
||||||
## More Information
|
## More Information
|
||||||
- [ArrayList Documentation](https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html)
|
- [ArrayList Documentation](https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html)
|
||||||
|
Reference in New Issue
Block a user