A huge limitation of arrays is that it has a fixed length, and can only store, one specific type of data.
An ArrayList is a solution for this issue.
An ArrayList object is dynamically sized, it can become smaller or larger as elements are added or removed.
It can store multiple types of data without specific limits.
It’s best to choose between an Array and ArrayList based on your needs and the functionality of the array.
ArrayLists are very adaptable, so if you need to make an ArrayList set to a specific type, you set it up as typed ArrayList.
ArrayList lunchBag = new ArrayList();
Apple red = lunchBag.get(1);
Integer n = new Integer (5);
Double x = new Double(6.1);
int a = n.intValue();
int y = x.doubleValue();
ArrayList list = new ArrayList();
list.add(“A”);
list.add(“B”);
list.add(0,”C”);
list.add(“D”);
list.set(2,”E”);
list.remove(1);
System.out.println(list);
Answer: It should print out “C E D”. This is because our list at first will be A B. Since we ask to add C to the index of 0 the array will look like this- C A B. Then D gets added to become C A B D. The B gets replaced with E to become C A E D. Then we remove A, because it’s at index 1. It becomes C E D.
Array | ArrayList |
---|---|
Arrays have a fixed length. | ArrayLists can resize when new elements are added to it. |
You don’t need to have an import statement to use an array. The only case to use an import statement in an array would be when the array has specific elements that require import statements. | You have to have an important statement, java.util.ArrayList, or the full name of the package when you use the ArrayList. |
Elements can be accessed with index notation. Ex: LibraryArray[3]; | Different methods are used to access the ArrayList. Ex: myList.get(2), myList.add(“Bob”) |
Arrays can contain primitive data types(int, float, double, boolean, and char), and/or object data types. | ArrayLists can only be used to hold object references. |
They can only hold one specific type of element. Ex: If the array is said to hold only integers, then it stores only integers, not other types such as Strings. | Has the ability to hold a collection of objects.**However, this isn’t recommended** Ex: ArrayList list = new ArrayList();list.add(new String(“Hello”));*list.add(new Integer(5)); |
\