Difference between Array and ArrayListIn Java, array and ArrayList are the well-known data structures. An array is a basic functionality provided by Java, whereas ArrayList is a class of Java Collections framework. It belongs to java.util package. Java ArrayAn array is a dynamically-created object. It serves as a container that holds the constant number of values of the same type. It has a contiguous memory location. Once an array is created, we cannot change its size. We can create an array by using the following statement: The above statement creates an array of the specified size. When we try to add more than its size, it throws ArrayIndexOutOfBoundsException. For example: Java ArrayList classIn Java, ArrayList is a class of Collections framework. It implements List<E>, Collection<E>, Iterable<E>, Cloneable, Serializable, and RandomAccess interfaces. It extends AbstractList<E> class. We can create an instance of ArrayList by using the following statement: ArrayList is internally backed by the array in Java. The resize operation in ArrayList slows down the performance as it involves new array and copying content from an old array to a new array. It calls the native implemented method System.arraycopy(sec, srcPos, dest, destPos, length) . We cannot store primitive type in ArrayList. So, it stores only objects. It automatically converts primitive type to object. For example, we have create an ArrayList object, The JVM converts it into Integer object through auto-boxing. Similarities
The following table describes the key differences between array and ArrayList:
Example of Array in JavaIn the following example, we have simply created an array of length four. Output: 12 2 15 67 Example of ArrayList in JavaIn the following example, we have created an instance of ArrayList and performing iteration over the ArrayList. Output: 12.4 34.6 56.8 78.9 Next TopicJava Tutorial |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India