java arraylist methods code example

Example 1: how to import an arraylist in java

import java.util.ArrayList;

Example 2: java arraylist

import java.util.List; //list abstract class
import java.util.ArrayList; //arraylist class

//Object Lists
List l = new ArrayList();
ArrayList a = new ArrayList();

//Specialized List
List l = new ArrayList();
ArrayList a = new ArrayList();
//only reference data types allowed in brackets <>

//Initial Capacity
List l = new ArrayList(5);
//list will start with a capacity of 5
//saves allocation times

Example 3: arraylist in java

import java.util.ArrayList;
public class ArrayListExample
{
   public static void main(String[] args)
   {
      int num = 14;
      // declaring ArrayList with initial size num
      ArrayList al = new ArrayList(num);
      // append new element at the end of list
      for(int a = 1; a <= num; a++)
      {
         al.add(a);
      }
      System.out.println(al);
      // remove element at index 7
      al.remove(7);
      // print ArrayList after deletion
      System.out.println(al);
      // print elements one by one
      for(int a = 0; a < al.size(); a++)
      {
         System.out.print(al.get(a) + " ");
      }
   }
}

Example 4: arraylist java methds

import java.util.ArrayList;
ArrayList myList = new ArrayList();
myList.add(0);
myList.remove(0);//Remove at index 0
myList.size();
myList.get(0);//Return element at index 0

Example 5: arraylist in java

Size is dynamic
Only supports objects
not syncronized
array based class

Tags:

Misc Example