From dac0ccfe2aec040f4930a23eba3f18240ec996ba Mon Sep 17 00:00:00 2001 From: Mallory Butt Date: Sat, 3 Nov 2018 19:08:02 -0500 Subject: [PATCH] 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 --- guide/english/java/arraylist/index.md | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/guide/english/java/arraylist/index.md b/guide/english/java/arraylist/index.md index 171e3c07ed..fe8380ca44 100644 --- a/guide/english/java/arraylist/index.md +++ b/guide/english/java/arraylist/index.md @@ -79,10 +79,27 @@ Since ArrayList implements *List*, an ArrayList can be created using the followi ```java 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. + + ## 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 - [ArrayList Documentation](https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html)