0% found this document useful (0 votes)
47 views14 pages

1602-19-733-014-Week8-Oop Lab

This document discusses serialization, collection frameworks, and collection interfaces in Java. It defines serialization as making objects transportable between applications by converting their state into a byte stream. It differentiates between the Serializable and Externalizable interfaces, noting that Serializable uses default serialization while Externalizable requires implementing serialization methods. It outlines the collection interfaces hierarchy with Collection, List, Set, and Map interfaces. It then explains the List and Set interfaces and provides examples using ArrayList, LinkedList, and HashSet.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views14 pages

1602-19-733-014-Week8-Oop Lab

This document discusses serialization, collection frameworks, and collection interfaces in Java. It defines serialization as making objects transportable between applications by converting their state into a byte stream. It differentiates between the Serializable and Externalizable interfaces, noting that Serializable uses default serialization while Externalizable requires implementing serialization methods. It outlines the collection interfaces hierarchy with Collection, List, Set, and Map interfaces. It then explains the List and Set interfaces and provides examples using ArrayList, LinkedList, and HashSet.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

WEEK 8:

Serialization & Collection


Framework: Set, List
1. Define the process of serialization
A)Serialization is the process of making any instance to be transportable

on the different application, domain, firewall and network.

2. Differentiate between Serializable and Externalizable


A)1) One of the obvious difference between Serializable and Externalizable is that
Serializable is a marker interface i.e. does not contain any method but Externalizable
interface contains two methods writeExternal() and readExternal().

2) The second difference between Serializable vs Externalizable is responsibility of


Serialization. when a class implements Serializable interface, default Serialization
process gets kicked of and that takes responsibility of serializing super class state.
When any class in
Java implement java.io.Externalizable than its your responsibility to implement
Serialization process i.e. preserving all important information.

3) This difference between Serializable and Externalizable is performance. You can not
do much to improve performance of default serialization process except reducing
number of fields to be serialized by using transient and static keyword but with
Externalizable interface you have full control over Serialization process.

4) Another important difference between Serializable and Externalizable interface is


maintenance. When your Java class implements Serializable interface its tied with
default representation which is fragile and easily breakable if structure of class changes
e.g. adding or removing field. By using java.io.Externalizable interface you can create
your own custom binary format for your object.
3.Write the Collection Interfaces hierarchy?

A)The hierarchy of the entire collection framework consists of four core


interfaces such as
Collection, List, Set, Map, and two specialized interfaces named SortedSet and
SortedMap for sorting.
All the interfaces and classes for the collection framework are located in
java.util package. The diagram of Java collection hierarchy is shown in the
below figure.
e➝ extends, I➝ implements

Extends: Extends is a keyword that is used for developing inheritance between two
classes and two interfaces.
Implements: Implements is a keyword used for developing inheritance between class
and interface.

3.Explain each of the collection classes defined using


List, Set interfaces?
A)The List interface extends Collection and declares the behavior of a
collection that stores a sequence of elements.

Elements can be inserted or accessed by their position in the list, using a zero-
based index.

A list may contain duplicate elements.

Several of the list methods will throw an UnsupportedOperationException if the


collection cannot be modified, and a ClassCastException is generated when
one object is incompatible with another.

import java.util.*; public class

CollectionsDemo {

public static void main(String[]

args) { List a1= new ArrayList();

a1.add("Zara");

a1.add("Mahnaz");

a1.add("Ayan");

System.out.println(" ArrayList Elements");

System.out.print("\t" + a1);

List l1= new LinkedList();

l1.add("Zara");
l1.add("Mahnaz");

l1.add("Ayan");

System.out.println();

System.out.println(" LinkedList Elements");

System.out.print("\t" + l1);

Output

ArrayList Elements

[Zara, Mahnaz, Ayan]

LinkedList Elements

[Zara, Mahnaz, Ayan]

A Set is a Collection that cannot contain duplicate elements. It models the


mathematical set abstraction.

The Set interface contains only methods inherited from Collection and adds
the restriction that duplicate elements are prohibited.

Set also adds a stronger contract on the behavior of the equals and hashCode
operations, allowing Set instances to be compared meaningfully even if their
implementation types differ.

public class SetDemo {

public static void main(String args[]) { int

count[] = {34, 22,10,60,30,22};

Set<Integer> set = new


HashSet<Integer>(); try { for(int i = 0; i <

5; i++) {

set.add(count[i]);

System.out.println(set);

TreeSet sortedSet = new TreeSet<Integer>(set);

System.out.println("The sorted list is:");

System.out.println(sortedSet);

System.out.println("The First element of the set is: "+


(Integer)sortedSet.first());

System.out.println("The last element of the set is: "+


(Integer)sortedSet.last());

} catch(Exception e)

{}

Outputs [34, 22,

10, 60, 30] The

sorted list is:

[10, 22, 30, 34, 60]

The First element of the set is: 10

The last element of the set is: 60


5. What is an Iterator & a ListIterator. How is it used
within various collection classes?
A)1) Iterator is used for traversinglist and set both.

We can use ListIterator to traverse list only, we cannot traverse set using ListIterator.

2) We can traverse in only forward direction using Iterator.

Using ListIterator, we can traverse a List in both the directions (forward and
Backward).
3) We cannot obtain indexes while using Iterator

We can obtain indexes at any point of time while traversing a list using ListIterator.
The methods nextIndex() and previousIndex() are used for this purpose.

4) We cannot add element to collection while traversing it using Iterator, it throws


ConcurrentModificationException when you try to do it.

We can add element at any point of time while traversing a list using ListIterator.

5) We cannot replace the existing element value when using Iterator.

By using set(E e) method of ListIterator we can replace the last element returned by
next() or previous() methods.

6) Methods of Iterator:

hasNext()
next()
remove()

Methods of ListIterator:

add(E e)
hasNext()
hasPrevious()
next()
nextIndex()
previous()
previousIndex()
remove()
set(E e)

7. How is a List different from a Set?

A)List is an ordered sequence of elements whereas Set is a distinct list of

elements which is unordered.

List <E>: An ordered collection (also known as a sequence). The user of

this interface has precise control over where in the list each element is

inserted. The user can access elements by their integer index (position in

the list), and search for elements in the list.

Set<E>: A collection that contains no duplicate elements. More formally,

sets contain no pair of elements e1 and e2 such that e1.equals(e2), and

at most one null element.

As implied by its name, this interface models the mathematical set


abstraction.

8. Define the keywords volatile & Transient

A)A volatile keyword is used in a multithreading environment where two

threads reading and writing the same variable simultaneously. The

volatile keyword flushes the changes directly to the main memory

instead of the CPU cache.


On the other hand, the transient keyword is used during serialization.

Fields that are marked as transient can not be part of the serialization

and deserialization. We don't want to save the value of any variable then

we use transient keyword with that

variable.

HOME WORK ON CURRENT


TOPICS
8.1. Demonstrate the process of serializing and deserializing a Student Object with
Volatile & Transient variables
A) import
java.util.*;

// Java code for serialization and deserialization


// of a Java object

import java.io.*; class

Student implements

java.io.Serializable

{ public int rollno;

public String

studentname;

// Default constructor public

Student(int a, String b)
{ this.rollno= rollno;

this.studentname= studentname;

} class
Test
{ public static void main(String[] args)

Student studobject = new Student(1, "chinmin");

String filename = "file.ser";

// Serialization

try

{
//Saving of object in a file

FileOutputStream file = new FileOutputStream(filename);

ObjectOutputStream out = new ObjectOutputStream(file);

// Method for serialization of object

out.writeObject(studobject);

out.close();

file.close();
System.out.println("Object has been serialized");

catch(IOException ex)

System.out.println("IOException is caught");

Student studobject1 = null;


// Deserialization

try

// Reading the object from a file

FileInputStream file = new FileInputStream(filename);

ObjectInputStream in = new ObjectInputStream(file);

// Method for deserialization of object

studobject1 = (Student)in.readObject();

in.close();

file.close();
System.out.println("Object has been deserialized ");

System.out.println("rollno.= " + studobject1.a);

System.out.println("stident name= " + studobject1.b);

catch(IOException ex)

System.out.println("IOException is caught");

}
catch(ClassNotFoundException ex)

System.out.println("ClassNotFoundException is caught");

}
}
OUTPUT;
Object has been serialized
Object has been deserialized
Roll no =1
Studentname=chinmin

8.2. Write a program to demonstrate Arraylist and demonstrate all the methods A)
import java.util.*; class JavaExample{ public static void main(String args[]){
ArrayList<String> alist=new ArrayList<String>();
alist.add("Adam");
alist.add("Tom");
alist.add("Lucky");
alist.add("Peora");
alist.add("Ankush");
alist.add("Tiger");
//displaying elements
System.out.println(alist);

//Adding "Steve" at the fourth position


alist.add(3, Adam");

//displaying elements
System.out.println(alist);
alist.remove("Adam");
alist.remove("Ankush");

//displaying elements
System.out.println(alist);

//Removing 3rd element


alist.remove(2);

//displaying elements
System.out.println(alist);
alist.set(0, "tittat");
System.out.println(alist);
}
}
OUTPUT:
[Adam,Tom,Lucky,Peora,Ankush,Tiger]
[Adam,Tom,Lucky,Adam,Peora,Ankush,Tiger]
[Tom,Lucky,Peora,Tiger]
[tittat,Lucky,Peora,Tiger]

8.3. Write a program to demonstrate Linkedlist and demonstrate all the methods
A) import
java.util.*;
public class LinkedListExample { public
static void main(String args[]) {

/* Linked List Declaration */


LinkedList<String> linkedlist = new LinkedList<String>();

/*add(String Element) is used for adding


* the elements to the linked list*/
linkedlist.add("Item1");
linkedlist.add("Item5");
linkedlist.add("Item3");
linkedlist.add("Item6");
linkedlist.add("Item2");

/*Display Linked List Content*/


System.out.println("Linked List Content: " +linkedlist);

/*Add First and Last Element*/


linkedlist.addFirst("First Item");
linkedlist.addLast("Last Item");
System.out.println("LinkedList Content after addition: " +linkedlist);

/*This is how to get and set Values*/


Object firstvar = linkedlist.get(0);
System.out.println("First element: " +firstvar);
linkedlist.set(0, "Changed first item");
Object firstvar2 = linkedlist.get(0);
System.out.println("First element after update by set method: " +firstvar2);

/*Remove first and last element*/


linkedlist.removeFirst();
linkedlist.removeLast();
System.out.println("LinkedList after deletion of first and last element: "
+linkedlist);

/* Add to a Position and remove from a position*/


linkedlist.add(0, "Newly added item");
linkedlist.remove(2);
System.out.println("Final Content: " +linkedlist);
}
}
8.4. Write a program to demonstrate HashSet and demonstrate all the methods
A) import
java.util.*; class
HashSet3{
public static void main(String args[]){
HashSet<String> set=new HashSet<String>();
set.add("Rajeev");
set.add("Vicky");
set.add("Anushka");
set.add("Suniel");
System.out.println("An initial list of elements: "+set);
//Removing specific element from HashSet
set.remove("Rajeev");
System.out.println("After invoking remove(object) method: "+set);
HashSet<String> set1=new HashSet<String>();
set1.add("Ajay");
set1.add("Gretha");
set.addAll(set1);
System.out.println("Updated List: "+set);
//Removing all the new elements from HashSet
set.removeAll(set1);
System.out.println("After invoking removeAll() method: "+set);
//Removing elements on the basis of specified condition
set.removeIf(str->str.contains("Vicky"));
System.out.println("After invoking removeIf() method: "+set);
//Removing all the elements available in the set
set.clear();
System.out.println("After invoking clear() method:
"+set); }
}

You might also like