Docsity

Java ArrayList, LinkedList and Iterator Demonstration, Study notes of Object Oriented Programming

Toggle sidebar
bg1
ArrayList Example
FileName:ArrayListDemo.java
import java.util.*;
class ArrayListDemo {
public static void main(String args[]) {
ArrayList al = new ArrayList();
System.out.println(“Initial size of al : “ + al.size());
// add elements to the array list
al.add(“C”); al.add(“A”);
al.add(“E”); al.add(“B”);
al.add(“D”); al.add(“F”); al.add(1, “A2”);
System.out.println(“Size of al after additions : “ +al.size());
// display the array list
System.out.println(“Contents of al: “ + al);
al.remove(“F”);
al.remove(2);
System.out.println(“size of al after deletions: “ + al.size());
System.out.println(“Contents of al: “ + al);
}
}
The output from this program is shown here:
Initial size of al: 0
Size of al after additions: 7
Contents of al: [C, A2, A, E, B, D, F]
Size of al after deletions: 5
Contents of al: [C, A2, E, B, D]
FileName:LinkedListDemo.java
pf3

Partial preview of the text

Download Java ArrayList, LinkedList and Iterator Demonstration and more Study notes Object Oriented Programming in PDF only on Docsity!

ArrayList Example FileName:ArrayListDemo.java

import java.util.*;

class ArrayListDemo {

public static void main(String args[]) { ArrayList al = new ArrayList(); System.out.println(“Initial size of al : “ + al.size()); // add elements to the array list al.add(“C”); al.add(“A”); al.add(“E”); al.add(“B”); al.add(“D”); al.add(“F”); al.add(1, “A2”); System.out.println(“Size of al after additions : “ +al.size()); // display the array list System.out.println(“Contents of al: “ + al); al.remove(“F”); al.remove(2); System.out.println(“size of al after deletions: “ + al.size()); System.out.println(“Contents of al: “ + al); }

}

The output from this program is shown here:

Initial size of al: 0 Size of al after additions: 7 Contents of al: [C, A2, A, E, B, D, F] Size of al after deletions: 5 Contents of al: [C, A2, E, B, D]

FileName: LinkedListDemo.java

import java.util. class LinkedListDemo { public static void main(String args[]) { LinkedList l1 = new LinkedList() ; l1.add(“F”); l1.add(“B”); l1.add(“D”); l1.add(“E”); l1.add(“C”); l1.addLast(“Z”); l1.addFirst(“A”); l1.add(1, “A2”); System.out.println(“Original contents of l1: “ + l1); l1.remove(“A”); l1.remove(1); System.out.println(“Contents of l1 after deletion: “ + l1); l1.removeFirst(); l1.removeLast(); System.out.println(“ l1 after deleting first and last: “ + l1); } } The output from this program is shown here: Original contents of l1: [A, A2, F, B, D, E, C, Z] Contents of l1 after deletion : [A2,B, D, E, C, Z] l1 after deleting first and last: [B, D, E, C]*

FileName: IteratorDemo.java import java.util.*; class IteratorDemo { public static void main(String args[]) { //create an array list ArrayList al = new ArrayList();