- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Initialize an ArrayList in Java
The ArrayList class extends AbstractList and implements the List interface. ArrayList supports dynamic arrays that can grow as needed. Array lists are created with an initial size. When this size is exceeded, the collection is automatically enlarged. When objects are removed, the array may be shrunk.
Let us now see how we can initialize an ArrayList with add() method −
Example
import java.util.ArrayList; import java.util.Collections; public class Demo { public static void main(String args[]) { ArrayList<Integer> myList = new ArrayList<Integer>(); myList.add(50); myList.add(29); myList.add(35); myList.add(11); myList.add(78); myList.add(64); myList.add(89); myList.add(67); System.out.println("Points
"+ myList); Collections.sort(myList); System.out.println("Points (ascending order)
"+ myList); } }
Output
Points [50, 29, 35, 11, 78, 64, 89, 67] Points (ascending) [11, 29, 35, 50, 64, 67, 78, 89]
Let us now see another way to initialize ArrayList using the asList() method −
Example
import java.util.*; public class Demo { public static void main(String args[]) { ArrayList<Integer> myList = new ArrayList<Integer>(Arrays.asList(50,29,35,11,78,64,89,67)); System.out.println("Points
"+ myList); Collections.sort(myList); System.out.println("Points (ascending order)
"+ myList); } }
Output
Points [50, 29, 35, 11, 78, 64, 89, 67] Points (ascending order) [11, 29, 35, 50, 64, 67, 78, 89]
Advertisements