Java Collection: ArrayList - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Community

Java Collection: ArrayList

Share This

The ArrayList class is used to store elements in a dynamic array.

The important facts about ArrayList class are:

  1. It can contain duplicate elements.
  2. Elements are stored according to insertion order.
  3. It is non synchronized.
  4. It allows random access because array works at the index basis.
  5. List manipulation is slow because a lot of shifting needs to be performed if any element is removed from the list or added in any position (except end).

Hierarchy of ArrayList class


ArrayList class inherits AbstractList class and implements List interface. The List interface inherits Collection and Iterable interfaces in hierarchical order.

Source code of Item.java
package com.t4b.test; public class Item { String name; int id; double price; public Item(String name, int id, double price) { super(); this.name = name; this.id = id; this.price = price; } }

Source code of TestMain.java
package com.t4b.test; import java.util.ArrayList; public class TestMain { public static void main(String[] args) { ArrayList<Item> items = new ArrayList<Item>(); // add items items.add(new Item("Apple", 1, 150.0)); items.add(new Item("Grape", 2, 250.0)); items.add(new Item("Bag", 3, 1050.0)); Item itm = new Item("Mango", 4, 100); items.add(itm); System.out.println(items.size()); // remove item items.remove(1); items.remove(itm); System.out.println(items.size()); ArrayList<Item> otherItems = new ArrayList<Item>(); otherItems.add(new Item("Bag", 3, 1050.0)); otherItems.add(new Item("Mango", 4, 100)); // add a list to another list System.out.println(items.size()); items.addAll(otherItems); System.out.println(items.size()); // iterate over the list for (Item i : items) { System.out.println(i); } } }

Happy Exploring!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.