Resizable Array in Java with ArrayList
Understanding through Code
import java.util.List; import java.util.ArrayList; public class ArrayListDemo { public static void main( String[] args ){ List<String> list = new ArrayList<>(); list.add("India"); list.add("US"); list.add("Canada"); System.out.println(list); list.add("Russia"); System.out.println(list); list.remove(1); System.out.println(list); String nation = list.get(0); System.out.println("The first nation is: " +nation); int pos = list.indexOf("Canada"); System.out.println("Canada is at: " +pos); } }
Output
- [India, US, Canada]
- [India, US, Canada, Russia]
- [India, Canada, Russia]
- The first nation is: India
- Canada is at: 1
Notes
- Collection framework is a set of interfaces or classes that make management of data easy.
- The two most commonly used frameworks are: ArrayList and HashMap.
- <String> is generic notation or diamond operator. It denotes the list contains what data type
- For integer we have to put helper class: <Integer>
- It is possible to create instance of interface ‘List’ but then we would have to implement all of the methods.
- We have called constructor of ArrayList. We don’t need to pass data type after ArrayList<>.