Similarities and differences between an Array and an ArrayList

 

Operation                 Array                         ArrayList
-----------------------------------------------------------------------------
Creation         String[] a = new String[10]   ArrayList<String> list = new ArrayList<>()
Access           a[index]                      list.get(index)
Update           a[index] = "London"           list.set(index, "London")
Size info        a.length		       list.size()
Append	                                       list.add("London")
Insert                                         list.add(index, "London")
Remove by index                                list.remove(index)
Remove element                                 list.remove(element)
Remove all                                     list.clear()


Find first occurrence list.indexOf(element) Find last occurrence list.lastIndexOf(element)

Caveat when using ArrayList

  • Important caveat when using ArrayList:

    • The ArrayList can only store data of the reference type

    I.e.:

    • An ArrayList cannot be used to store data of a primitive data type (such as int, double, etc)

  • Example: this program will generate a compile error:

     public class Error
     {
         public static void main(String[] args)
         {
             ArrayList<int> myList = new ArrayList<>(); // Compile error
         }
     }

  • We will solve this problem in the next chapter (with wrapper classes)

DEMO: demo/11-arrayList/06-prim-type/Error.java