Lab 07 PDF
Lab 07 PDF
Lab 07 PDF
ghfhj
1. Anonymous inner classes
2. List, Arraylist, Iterator, ListIterator and Linked Lists
CS F213 (Lab 7)
Page 1 of 16
In the above example the EnglishMovie is inner class and for the instance hindiMovie we
created Anonymous inner class .
CS F213 (Lab 7)
Page 2 of 16
1.2 Exercise:
public class Anonymous {
public Circle getCircle(int radius) {
// Write one line statement that returns object of Circle
}
public static void main(String[] args) {
Anonymous p = new Anonymous();
Circle w = p.getCircle(10);
// The output here should give correct value of area
// of the circle.
System.out.println(w.area());
}
}
class Circle {
private int rad;
public Circle(int radius) { rad = radius; }
public double area() { return rad*rad; }
}
2. List Interface
A List is an ordered Collection (sometimes called a sequence). The user of this interface has precise
control over where in the list each element is inserted. In addition to the operations inherited
from Collection, the List interface includes operations for the following:
Positional access manipulates elements based on their numerical position in the list
Search searches for a specified object in the list and returns its numerical position
Iteration extends Iterator semantics to take advantage of the list's sequential nature
Range-view performs arbitrary range operations on the list.
CS F213 (Lab 7)
Page 3 of 16
3. ArrayList
It is resizable-array implementation of the List interface. Implements all optional list operations,
and permits all elements, including null.
ArrayList supports dynamic arrays that can grow as needed unlike standard Java arrays which are
of a fixed length.
In addition to implementing the List interface, this class provides methods to manipulate the size
of the array that is used internally to store the list.
3.1 Example: Following example shows the use of ArrayList and its methods.
import java.util.ArrayList;
public class ArrayListDemo {
public static void main(String[] args) {
//Creating a new ArrayList
ArrayList arlTest = new ArrayList();
//Size of arrayList
System.out.println("Size of ArrayList at creation: "
+arlTest.size());
//Lets add some elements to it
arlTest.add("B");
arlTest.add("I");
arlTest.add("T");
arlTest.add("S");
//Recheck the size after adding elements
System.out.println("Size of ArrayList after adding
elements: "+arlTest.size());
//Display all contents of ArrayList
System.out.println("List of all elements: " +
arlTest);
//Remove some elements from the list
arlTest.remove("B");
System.out.println("See contents after removing one
element: " + arlTest);
//Remove element by index
arlTest.remove(2);
System.out.println("See contents after removing
element by index: " + arlTest);
//Check size after removing elements
System.out.println("Size of arrayList after removing
elements: " + arlTest.size());
System.out.println("List of all elements after
removing elements: " + arlTest);
CS F213 (Lab 7)
Page 4 of 16
4. Iterator
Each of the collection classes provides an iterator( ) method that returns an iterator to the start
of the collection. By using this iterator object, you can access each element in the collection,
one element at a time. In general, to use an iterator to cycle through the contents of a collection,
follow these steps:
1. Obtain an iterator to the start of the collection by calling the collection's iterator( )
2. Set up a loop that makes a call to hasNext( ). Have the loop iterate as long as hasNext( )
returns true.
3. Within the loop, obtain each element by calling next( ).
5. ListIterator
An iterator for lists that allows the programmer to traverse the list in either direction, modifies the
list during iteration, and obtains the iterator's current position in the list. A ListIterator has no
current element; its cursor position always lies between the element that would be returned by a
call to previous() and the element that would be returned by a call to next().
An iterator for a list of length n has n+1 possible cursor positions, as illustrated by the carets (^)
below:
Element(0) Element(1) Element(2) ... Element(n-1)
cursor positions:^
CS F213 (Lab 7)
Student {
String name;
String gender;
int age;
Page 5 of 16
(2) TestStudentList.java
// Demonstrate Iterator and ListIterator
import java.util.*;
public class TestStudentList {
public static void main(String args[]) {
// create an array list
ArrayList studentList = new ArrayList();
// add elements to the array list
studentList.add(new Student("Ramesh","Male",18));
studentList.add(new Student("Reeta","Female",19));
studentList.add(new Student("Seema","Female",18));
studentList.add(new Student("Suresh","Male",20));
System.out.println("Original contents of
studentList:");
Iterator itr = studentList.iterator();
while(itr.hasNext()) {
Object element = itr.next();
System.out.print(element +"\n");
}
CS F213 (Lab 7)
Page 6 of 16
System.out.println();
// modify objects being iterated
ListIterator litr = studentList.listIterator();
while(litr.hasNext()) {
Student element = (Student)litr.next();
if(element.getGender().equals("Male")){
element.setName("Mr."+element.getName());
}
else{
element.setName("Miss."+element.getName());
}
litr.set(element);
}
System.out.println("Modified contents of studentList:
");
itr = studentList.iterator();
while(itr.hasNext()) {
Object element = itr.next();
System.out.print(element + "\n");
}
System.out.println();
// now, display the list backwards
System.out.println("Modified list backwards: ");
while(litr.hasPrevious()) {
Object element = litr.previous();
System.out.print(element + "\n");
}
System.out.println();
}
}
Exercise:
The L&L Bank can handle up to 30 customers who have savings accounts. Design and implement
a program that manages the accounts. Keep track of key information and allow each customer to
make deposits and withdrawals. Produce appropriate error messages for invalid transactions. Do
this practice problem using ArrayList and Iterator.
CS F213 (Lab 7)
Page 7 of 16
(B) Complete the code of Bank class as per the commented instructions
public class Bank {
private ArrayList<Account> accts;
int maxActive;
public boolean addAccount (Account newone) {
/* Write the code for adding new account, return false if
account cant be created */
}
public boolean removeAccount (long acctnum) {
/* Write the code for removing the account, return false if
account does not exist */
}
public double deposit(long acctnum, double amount) {
/* Write the code for depositing specified amount to the
account,
return -1 if account does not exist */
}
public double withdraw(long acctnum, double amount) {
/* Write the code for withdrawing specified amount from
the account,
return -1 if insufficient balance or account does not
exist */
}
//override toString() method to display details of all the
accounts in bank
}
(C) Write a suitable driver class to test the behavior of the methods of above classes.
CS F213 (Lab 7)
Page 8 of 16
6. LinkedList
A linked list is a linear data structure where each element is a separate object. In a singly linked
list each node in the list stores the contents of the node and a pointer or reference to the next
node in the list. It does not store any pointer or reference to the previous node. It is called a
singly linked list because each node only has a single link to another node. To store a single
linked list, you only need to store a reference or pointer to the first node in that list. The last node
has a pointer to nothingness to indicate that it is the last node.
CS F213 (Lab 7)
Page 9 of 16
CS F213 (Lab 7)
Page 10 of 16
CS F213 (Lab 7)
Page 11 of 16
x = x.next;
x.next = new Node(data, x.next);
size++;
}
}
//Fetching a Node of a particular index
public Object getElement(int index) {
if( checkElementIndex(index)==-1)return null;
Node x = head;
for (int i = 0; i < index; i++)
x = x.next;
return x.data;
}
//Removing the head Node of Linked List
public Object removeFirst() {
if (size == 0)
return null;
else {
Object temp = head.data;
head = head.next;
size--;
return temp;
}
}
//Removing the last Node of Linked List
public Object removeLast() {
if (size <= 1)
return removeFirst();
else {
Node x = head;
while (x.next.next != null)
x = x.next;
Object temp = x.next.data;
x.next = null;
size--;
return temp;
}
}
//Removing the a particular Node of LinkedList
public void remove(int index) {
if(checkElementIndex(index)==-1)return;
if (index == 0)
removeFirst();
else {
Node x = head;
for (int i = 0; i < index - 1; i++)
x = x.next;
x.next = x.next.next;
size--;
}
}
//Changing data value of a particular Node
public Object setElement(int index, Object newData) {
CS F213 (Lab 7)
Page 12 of 16
if(checkElementIndex(index)==-1)return null;
Node x = head;
for (int i = 0; i < index; i++)
x = x.next;
Object temp = x.data;
x.data = newData;
return temp;
}
//Returns the index of the first occurrence of the data
public int indexOf(Object data) {
Node x = head;
for (int i = 0; i < size; i++, x = x.next)
if (x.data.equals(data)) {
return i;
}
return -1;
}
//Returns the index of the last occurrence of the data
public int lastIndexOf(Object data) {
int lastOccurrence = -1;
Node x = head;
for (int i = 0; i < size; i++, x = x.next)
if (x.data.equals(data))
lastOccurrence = i;
return lastOccurrence;
}
//Helper Methods
//Checks whether a particular object is there in the list
public boolean contains(Object o) {
for (Node x = head; x != null; x = x.next) {
if (x.data.equals(o)) {
return true;
}
}
return false;
}
//Checks whether a particular index is feasible or not
private int checkElementIndex(int index) {
if (index < 0 || size <= index)
return -1;
return 1;
}
//Checks whether list is empty or not
public boolean isEmpty() {
return head == null;
}
// Returns the size of list
public int getSize() {
return size;
}
public String toString() {
if (head == null) {
return "null";
CS F213 (Lab 7)
Page 13 of 16
} else {
StringBuilder stringView = new StringBuilder();
StringBuilder inside loops is very efficient
for (Node x = head; x != null; x = x.next)
stringView.append(x.toString());
return stringView.toString();
}
}
// using
Exercises:
1. Add a function in the MyLinkedList class to reverse the given linked list. The function
should return the new head of the linked list.
2. Add a function in the MyLinkedList class to rotate the given linked list counterclockwise by k nodes. The function should return the new head of the linked list. For
example, if the given linked list is 10->20->30->40->50->60 and k is 4, the list should be
modified to 50->60->10->20->30->40. Assume that k is smaller than the count of nodes
in linked list and positive.
CS F213 (Lab 7)
Page 14 of 16
CS F213 (Lab 7)
Page 15 of 16
The two node links allow traversal of the list in either direction. While adding or removing a
node in a doubly-linked list requires changing more links than the same operations on a singly
linked list, the operations are simpler and potentially more efficient, because there is no need to
keep track of the previous node during traversal or no need to traverse the list to find the
previous node, so that its link can be modified.
Exercises:
1. Implement a Doubly Linked List in Java having all the functions implemented as shown
for Singly Linked List.
2. Create an iterator for the same as an inner class.
CS F213 (Lab 7)
Page 16 of 16