[Go to site: main page, start]

0% found this document useful (0 votes)
2 views108 pages

Java Module1

Uploaded by

sanjanav762
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views108 pages

Java Module1

Uploaded by

sanjanav762
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

ADVANCED

JAVA
BCS613D

- Dr. SANTOSH K C
ASSOCIATE PROFESSOR
Dept. of C S & E
BIET, DAVANGERE
MODULE-1
The collections and Framework:
 Collections Overview, The Collection Interfaces.
 The Collection Classes, accessing a collection Via an
Iterator.
 Storing User Defined Classes in Collections, The
Random Access Interface.
 Working with Maps, Comparators, The Collection
Algorithms.
 Arrays, The legacy Classes and Interfaces.
 Parting Thoughts on Collections.
The History and Evolution of Java
■ Java’s Lineage
Java is related to C++, which is a direct descendant of
C. Much of the character of Java is inherited from these
two languages. From C, Java derives its syntax. Many of
Java’s object oriented features were influenced by C++.
■ FORTRAN, BASIC
■ The Birth of Modern Programming:
C, C++
■ The Stage Is Set for Java
■ The Creation of Java
Java was conceived by James Gosling, Patrick Naughton,
Chris Warth, Ed Frank, and Mike Sheridan at Sun Microsystems,
Inc. in 1991.
-Portable, Platform-independent
-Internet version of C++
How Java Impacted the Internet
• Java Applets
• Security
• Portability
The Java Buzzwords
• Simple
• Secure
• Portable
• Object-oriented
• Robust
• Multithreaded
• Architecture-neutral
• Interpreted
• High performance
• Distributed
• Dynamic
An Overview of Java
■ The Three OOP Principles
i. Encapsulation: Encapsulation is the mechanism that
binds together code and the data it manipulates, and keeps both
safe from outside interference and misuse.
ii. Inheritance: Inheritance is the process by which one
object acquires the properties of another object.
iii. Polymorphism: Polymorphism (from Greek, meaning
“many forms”) is a feature that allows one interface to be used for
a general class of actions.
■ Polymorphism, Encapsulation, and Inheritance Work
Together
■ A First Simple Program
/* This is a simple Java program.
Call this file "[Link]". */
class Example { // Your program begins with a call to main().
public static void main(String[ ] args)
{
[Link]("This is a simple Java program.");
}
}
A Second Short Program
/* Here is another short example.
Call this file "[Link]". */
class Example2
{
public static void main(String[ ] args)
{
int num; // this declares a variable called num
num = 100; // this assigns num the value 100
[Link]("This is num: " + num);
num = num * 2;
[Link]("The value of num * 2 is ");
[Link](num);
}
}
■ Two Control Statements
The if Statement
The Java if statement works much like the IF statement in any
other language. It determines the flow of execution based on
whether some condition is true or false. Its simplest form is
shown here:
• Syntax: if(condition) statement;

if(num < 100)


[Link]("num is less than 100");
class If Sample
{ public static void main(String[] args)
{
int x, y;
x = 10;
y = 20;
if(x < y)
[Link]("x is less than y");
x = x * 2;
if(x == y)
[Link]("x now equal to y");
X = x * 2;
if(x > y)
[Link]("x now greater than y");
// this won't display anything if(x == y) [Link]("you won't
see this");
}
}
■ The for Loop
Loop statements are an important part of nearly any programming
language because they provide a way to repeatedly execute some
task.

for(initialization; condition; iteration) statement;


class ForTest
{
public static void main(String[] args)
{
int x;
for(x = 0; x<10; x = x+1)
[Link]("This is x: " + x);
}
}
Data Types
■ The Primitive Types
– Integers
– Floating-point numbers
– Characters
– Boolean
Variables
■ Type Conversion and Casting
Arrays
– One-Dimensional Arrays
– Multidimensional Arrays
■ Operators
■ Introducing Classes
– The class is at the core of Java. It is the logical construct upon which
the entire Java language is built because it defines the shape and nature of
an object.
■ The General Form of a Class
– When you define a class, you declare its exact form and nature.
– A class is declared by use of the class keyword.
class classname {
type instance-variable1;
type instance-variable2; // ...
type instance-variableN;
type methodname1(parameter-list) {
// body of method
}
type methodname2(parameter-list) {
} type methodnameN(parameter-list) { } } //
A Simple Class
class Box
{
double width;
double height;
double depth;
}

Box mybox = new Box( ); // create a Box object called


mybox
■ Thus, every Box object will contain its own copies of
the instance variables width, height, and depth.
■ To access these variables, you will use the dot (.)
operator.
For example, to assign the width variable of mybox the
value 100, you would use the following statement:
[Link] = 100;
Ex: Program that uses the Box class:
class Box {
double width; double height; double depth;
}
class BoxDemo {
public static void main(String[] args)
{
Box mybox = new Box();
double vol;
[Link] = 10;
[Link] = 20;
[Link] = 15;
vol = [Link] * [Link] * [Link];
[Link]("Volume is " + vol);
}
}
Declaring Objects
Box mybox = new Box();

Box mybox; // declare reference to object


mybox = new Box(); // allocate a Box object
Figure 1 Declaring an object of type Box
■ Introducing Methods
General form of a method:

type name(parameter-list)
{
// body of method
}
// This program includes a method inside the box class.
class Box
{
double width; double height;
double depth;
// display volume of a box
void volume()
{ [Link]("Volume is ");
[Link](width * height * depth);
}
}
class BoxDemo3 {
public static void main(String[] args)
{
Box mybox = new Box();
[Link] = 10;
[Link] = 20;
[Link] = 15;
// display volume of box
[Link]();
}
}
Garbage Collection
• Since objects are dynamically allocated by using the new operator.
• delete operator used in C++.
• Deallocation done automatically in java.
How Garbage Collection Works
An object becomes eligible for garbage collection when:
• It has no reference pointing to it
• It becomes unreachable in the program
[Link]
The Collections Framework
What is [Link]?
[Link] is a built-in package in Java that contains many ready-
made classes and interfaces. These help programmers do common
tasks easily instead of writing everything from scratch.
Inside [Link], there is a very powerful system called
the Collections Framework. It helps to manage groups of objects.
For example:
■ Storing multiple student names
■ Keeping a list of numbers
■ Managing sets of data
It includes:
■ Interfaces (like rules or blueprints)
■ Classes (ready-made implementations)
Examples:
■ ArrayList
■ HashSet
■ HashMap
These make storing and handling data much easier and more efficient.
import [Link];
import [Link];
public class CollectionExample {
public static void main(String[] args) {
// Collection interface reference
Collection<String> names = new ArrayList<>();
// Adding elements
[Link](”Amar");
[Link]("Akbar");
[Link](”Anthony");
// Displaying elements
[Link]("Student Names: " + names);
// Checking size
[Link]("Total Students: " + [Link]());
// Removing an element
[Link]("Anthony");
[Link]("After Removal: " + names);
}
}
What This Program Shows:
• Collection<String> → Using Collection Interface
• ArrayList<> → Implementation class
• add() → Adds elements
• size() → Returns number of elements
• remove() → Removes element
Collections Overview
Why Collections Were Introduced?
In early Java (before J2SE 1.2), there were classes like:
• Vector
• Stack
• Dictionary
• Properties

They could store objects, but:


• They were not uniform (each worked differently)
• They were hard to extend
• No common design
■ So Java introduced the Collections Framework to solve these problems.
What is Collections Framework?
■ It is a standard system or a well-organized storage system with
proper rules and structure.
Goals of Collections Framework
1. High Performance
Ready-made data structures like:
• Dynamic Arrays
• Linked Lists
• Trees
• Hash Tables
■ They are already optimized. Developer don’t need to write them.
2. Same Working Style
Different collections follow similar methods.
Example:
• Adding elements
• Removing elements
• Searching elements
3. Easy to Extend
The framework is built on interfaces (like blueprints).
Examples:
• List
• Set
• Map
Java gives ready-made classes like:
• LinkedList
• HashSet
• TreeSet
4. Algorithms in Collections
Java provides a class called:
Collections (notice capital C)
It contains ready-made static methods like:
• Sorting
• Searching
• Reversing
• Shuffling
The Collection Interface
The Collection Interface is the root interface of the Java Collections
Framework. Any class that represents a group of objects (like lists, sets, etc.)
must implement this interface.
It is declared as:
interface Collection<E>
Here, E represents the type of elements the collection will store (Generics).

Example:
Collection<String> names;
Collection<Integer> numbers;
Relationship with Iterable
Collection extends Iterable, every collection can be used in a
for-each loop.
Example:
for(String name : names)
{
[Link](name);
}
Core Methods of Collection
All collections (like List, Set, Queue) inherit these common methods.
➤ Adding Elements
• add(E e) → Adds one element
• addAll(Collection c) → Adds all elements from another collection
Example:
[Link]("Java");
[Link](otherList);
Removing Elements
• remove(Object o) → Removes one element
• removeAll(Collection c) → Removes all matching elements
• retainAll(Collection c) → Keeps only specified elements
• removeIf(Predicate) → Removes elements based on condition
• clear( ) → Removes everything
Example:
[Link]("Java");
[Link]();
Checking Elements
• contains(Object o) → Checks if element exists
• containsAll(Collection c) → Checks if all elements exist
• isEmpty() → Checks if collection is empty
• size( ) → Returns number of elements
Example:
if([Link]("Java")) {
[Link]("Found!");
}
➤ Iteration Methods
• iterator( ) → Returns Iterator
• spliterator( ) → Used for parallel processing
• stream( ) → Returns Stream
• parallelStream( ) → Returns parallel Stream
Example:
[Link]().forEach([Link]::println);
Possible Exceptions
Some methods may throw exceptions:

Exception When It Happens


UnsupportedOperationException If collection is unmodifiable
ClassCastException Wrong type of object added
NullPointerException Null not allowed
IllegalArgumentException Invalid argument
IllegalStateException Collection is full (fixed size)
■ The Collection interface defines the basic rules and
methods that every group-of-objects class must follow in Java.
■ It gives standard methods to add, remove, check, iterate, and
convert elements.
■ Without Collection, Java would not have a structured and
consistent data storage system.
The JCF Interfaces
The Java Collections Framework defines several interfaces.
The java collection interfaces is necessary because they determine the
fundamental nature of the collection classes.
The List Interface
• 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.
List is a generic interface that has this declaration:
interface List<E>
• Here, E specifies the type of objects that the list will hold.
Some operations of List:
■ To obtain the object stored at a specific location, call get( ) with
the index of the object.
■ To assign a value to an element in the list, call set( ), specifying
the index of the object to be changed.
■ To find the index of an object, use indexOf( ) or lastIndexOf( ).
■ Sublist of a list can obtain by calling subList( ),

Ex: E get(int index),


int indexOf(Object obj),
E set(int index, E obj)
The Set Interface
• The Set interface defines a set.
• It extends Collection and specifies the behavior of a collection
that does not allow duplicate elements.
• Therefore, the add( ) method returns false if an attempt is made to
add duplicate elements to a set.
Set is a generic interface that has this declaration:
interface Set<E>
Example:
Set<String> names = new HashSet< >(
);
[Link]("Java");
[Link]("Python");
[Link]("C++")
[Link]("Java"); // Duplicate
[Link](names);

O/P:
Java
Python
C++
The SortedSet Interface
• The SortedSet interface extends Set and declares the behavior of
a set sorted in ascending order.
SortedSet is a generic interface that has this declaration:
interface SortedSet<E>
• Here, E specifies the type of objects that the set will hold.
Ex 1:
SortedSet<Integer> nums = new
TreeSet<>();

[Link](50);
[Link](10);
[Link](30);
[Link](10); // duplicate

[Link](nums);

O/P:
EX 2:
SortedSet<Integer> nums = new TreeSet<>();
[Link](10);
[Link](20);
[Link](30);
[Link](40);
[Link]([Link]());
[Link]([Link]());
[Link]([Link](30));

O/P:
10
40
10, 20
The NavigableSet Interface
• The NavigableSet interface extends SortedSet and declares the
behavior of a collection that supports the retrieval of elements
based on the closest match to a given value or values.
• NavigableSet is a generic interface that has this declaration:
interface NavigableSet<E>
NavigableSet<Integer> nums = new TreeSet<>();
[Link](10);
[Link](20);
[Link](30);
[Link](40);

[Link]([Link](25));
[Link]([Link](20));
[Link]([Link](25));
[Link]([Link](30));

O/P:
20
20
30
40
The Queue Interface
The Queue interface extends Collection and declares the behavior
of a queue, which is often a first-in, first-out list
interface Queue<E>
import [Link];
import [Link];

public class QueueExample {


public static void main(String[] args) {

Queue<String> queue = new LinkedList<>();


// Adding elements
[Link]("Ravi");
[Link]("Anu");
[Link]("Kiran");

[Link]("Queue: " + queue);


// Removing element (FIFO)
[Link]("Removed: " + [Link]());

[Link]("After removal: " + queue);


// Viewing head element
[Link]("Front element: " + [Link]());
}
}
The Collection Classes

Now that we are familiar with the collection interfaces, we are


ready to examine the standard classes that implement them.
Some of the classes provide full implementations that can be used
as-is. Others are abstract, providing skeletal implementations
that are used as starting points for creating concrete collections.
The standard collection classes are summarized in the following table
The ArrayList Class
The ArrayList class extends AbstractList and implements the List interface.
ArrayList is a generic class that has this declaration:
class ArrayList <E>
ArrayList supports dynamic arrays that can grow as needed.

ArrayList has the constructors shown here:


ArrayList( ) Builds an empty array list.
Builds an array list that is initialized with
ArrayList(Collection <?extends E> c ) the elements of the collection c.

ArrayList(int capacity) Builds an array list that has the


specified initial capacity.
The following program shows a simple use of ArrayList.
• An array list is created for objects of type String, and then several strings are
added to it.
• The list is then displayed.
• Some of the elements are removed and the list is displayed again.

// Demonstrate ArrayList.
import [Link].*; //Import Statement
class ArrayListDemo { //Declares a class named ArrayListDemo.
public static void main(String args[])
{ //Creating an ArrayList
ArrayList al = new ArrayList();
[Link]("Initial size of al: " + [Link]());
// Add elements to the array list.
[Link]("C");
[Link]("A");
[Link]("E");
[Link]("B");
[Link]("D");
[Link]("F"); // Adds elements "C", "A", "E", "B", "D", "F" sequentially.
[Link](1, "A2");
[Link]("Size of al after additions: " + [Link]());
// Display the array list
[Link]("Contents of al: " + al);
// Remove elements from the array list.
[Link]("F"); //Removes element "F" from the list.
[Link](2);
[Link]("Size of al after deletions: " + [Link]());
[Link]("Contents of al: " + al);
}
}
Output:

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]

The contents of a collection are displayed using the default conversion


provided by toString( ), which was inherited from AbstractCollection.
The LinkedList Class
The LinkedList class extends AbstractSequentialList and implements
the List, Deque, and Queue interfaces.
It provides a linked-list data structure.
LinkedList is a generic class that has this declaration:
class LinkedList <E>

LinkedList has the two constructors shown here:


LinkedList( )
LinkedList(Collection <?extends E> c)
The first constructor builds an empty linked list.
The second constructor builds a linked list that is initialized with the
elements of the collection c
Because LinkedList implements the Deque interface, we have access
to the methods defined by Deque.
Example:
To add elements to the start of a list, use addFirst( ) or offerFirst( ).
To add elements to the end of the list, use addLast( ) or offerLast( ).
To obtain the first element, use getFirst( ) or peekFirst( ).
To obtain the last element, use getLast( ) or peekLast( ).
To remove the first element, use removeFirst( ) or pollFirst( ).
To remove the last element, use removeLast( ) or pollLast( ).
// Demonstrate LinkedList. // Remove elements from the linked
list.
import [Link].*; [Link]("F");
[Link](2);
class LinkedListDemo { [Link]("Contents of ll
public static void main(String args[]) after deletion: " + ll);
// Remove first and last elements.
{ [Link]();
// Create a linked list.
LinkedList<String> ll = new [Link]();
LinkedList<String>( ); [Link]("ll after
// Add elements to the linked list. deleting first and last: "+ ll);
[Link]("F");
[Link]("B"); String val = [Link](2);
[Link]("D"); [Link](2, val + " Changed");
[Link]("E"); [Link]("ll after
[Link]("C"); change: " + ll);
[Link]("Z"); }
[Link]("A"); }
[Link](1, "A2");
[Link]("Original contents of ll: " + ll);
Output from this program is shown here:

Original contents of ll: [A, A2, F, B, D, E, C, Z]


Contents of ll after deletion: [A, A2, D, E, C, Z]
ll after deleting first and last: [A2, D, E, C]
ll after change: [A2, D, E Changed, C]
The EnumSet Class
● EnumSet extends AbstractSet and implements Set. It is specifically for
use with keys of an enum type.
● It is a generic class that has this declaration:
class EnumSet< E extends Enum <E>>

● EnumSet defines no constructors. Instead, it uses the factory methods


shown in Table 17-7 to create objects. All methods can throw
NullPointerException. The copyOf( ) and range( ) methods can also
throw IllegalArgumentException.
Accessing a Collection via an Iterator
• Using an Iterator object to go through the elements of a collection one by
one.
• Iterator helps us traverse (visit) each element in a collection like
ArrayList, HashSet, etc.
• Iterator enables you to cycle through a collection, obtaining or removing
elements.
• ListIterator extends Iterator to allow bidirectional traversal of a list, and
the modification of elements.
The Iterator interface declares the methods shown in Table 17-8
Using an Iterator
● By using this iterator object, we 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( ) method.
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( ).
Demonstrating both the Iterator and ListIterator interfaces. It
uses an ArrayList object
// Demonstrate iterators.
import [Link].*;
class IteratorDemo { // Modify objects being iterated.
public static void main(String args[]) { ListIterator<String> litr = [Link]();
// Create an array list. while([Link]()) {
ArrayList<String> al = new ArrayList<String>(); String element = [Link]();
// Add elements to the array list.
[Link]("C"); [Link](element + "+");
[Link]("A"); }
[Link]("E"); [Link]("Modified contents of al:
[Link]("B"); ");
[Link]("D"); itr = [Link]();
[Link]("F");
// Use iterator to display contents of al. while([Link]()) {
[Link]("Original contents of al: ");
Iterator<String> itr = [Link](); String element = [Link]();
while([Link]()) { [Link](element + " ");
String element = [Link](); }
[Link](element + " ");
} [Link]();
// Now, display the list backwards.
[Link]("Modified list
backwards: "); Output:
while([Link]()) { Original contents of al: C A E B D F
String element = [Link](); Modified contents of al:
[Link](element + " ");
C+ A+ E+ B+ D+ F+
Modified list backwards:
}
F+ D+ B+ E+ A+ C+
[Link]();
}
}
Storing User-Defined Classes in Collections

● For the sake of simplicity, the foregoing examples have stored built-
in objects, such as String or Integer, in a collection. Of course,
collections are not limited to the storage of built-in objects.
● For example, consider the following example that uses a LinkedList
to store mailing addresses:
class MailList {
// A simple mailing list example.
public static void main(String args[]) {
import [Link].*;
LinkedList<Address> ml = new
class Address {
LinkedList<Address>();
private String name, street, city, state, code;
Address(String n, String s, String c,
// Add elements to the linked list.
String st, String cd) {
[Link](new Address("J.W. West", "11 Oak Ave",
name = n;
"Urbana", "IL", "61801"));
street = s;
city = c;
[Link](new Address("Ralph Baker", "1142 Maple
state = st;
Lane", "Mahomet", "IL", "61853"));
code = cd;
}
[Link](new Address("Tom Carlton", "867 Elm St",
public String toString()
"Champaign", "IL", "61820"));
{
return name + "\n" + street + "\n" +
// Display the mailing list.
city + " " + state + " " + code;
for(Address element : ml)
}
[Link](element + "\n");
}
[Link]();
}
}
The RandomAccess Interface
The RandomAccess is a special interface in Java used in the Java
Collections Framework. But it is a marker interface.

What is a Marker Interface?


A marker interface is an interface that does not contain any methods.
Its purpose is just to mark or indicate something about a class.
So RandomAccess has no methods inside it.

What does RandomAccess indicate?


If a collection class implements RandomAccess, it means:
The collection can access elements quickly using an index
Classes that implement RandomAccess
Some collection classes support fast random access.
Examples:
• ArrayList
• Vector
These store elements like arrays, so accessing by index is very fast.
Example:
ArrayList<String> list = new ArrayList<>();
[Link]("Java");
[Link]("Python");

[Link]([Link](1));
Working with Maps
A map is an object that stores associations between keys and values, or
key/value pairs. Given a key, you can find its value.
Both keys and values are objects. The keys must be unique, but the values
may be duplicated. Some maps can accept a null key and null values,
others cannot.
Maps don’t implement the Iterable interface.
We can’t obtain an iterator to a map.
The Map Interfaces
The Map Interface
The Map interface maps unique keys to values. A key is an object that we
use to retrieve a value at a later date.
Given a key and a value, we can store the value in a Map object. After the
value is stored, we can retrieve it by using its key.
Map is generic and is declared as shown here:
interface Map <K, V>
Here, K specifies the type of keys, and V specifies the type of values.
Maps methods
Map stores Key–Value pairs
A Map stores data like this:
Key → Value
Example in Java:
Map<Integer, String> map = new HashMap< >( );

[Link](1, "Java");
[Link](2, "Python");
[Link](3, "C++");
Keys must be unique
In a Map, keys cannot be duplicated.

Example:
[Link](1, "Java");
[Link](1, "Python");
Comparators

In the Java Collections Framework, a Comparator is used to define how


objects should be sorted.
It is commonly used with sorted collections like:
• TreeSet
• TreeMap
■ These collections automatically store elements in sorted order.
Default Sorting (Natural Ordering)
By default, Java sorts data using natural ordering.
Examples:
Numbers → 1, 2, 3, 4
Letters → A, B, C, D
Example:
TreeSet<Integer> numbers = new TreeSet< >( );
[Link](5);
[Link](1);
[Link](3);
Output:
135
What is Comparator?
A Comparator lets you change the way elements are sorted.
For example:
• Reverse order
• Sort by length
• Sort by age
• Sort by name
So,
Comparator Interface
Declaration:
interface Comparator<T>
compare( ) Method
Main method of Comparator:
int compare(T obj1, T obj2)
This method compares two objects.
Return Value Meaning
0 Objects are equal
Positive Obj1 > Obj2
Negative Obj1 < Obj2

Example logic:
compare(5,3) → positive
compare(3,5) → negative
compare(4,4) → 0
The Collection Algorithms
The Collections Framework defines several algorithms that can be applied
to collections and maps. These algorithms are defined as static methods
within the Collections class. They are summarized in Table 20-15.
Arrays
In Java, the Arrays class provides ready-made static methods to work
easily with arrays.
These methods help perform common operations like searching, copying,
comparing, and converting arrays to lists.
■ Think of it as a toolbox for arrays 🧰
asList( ) Method
Purpose
Converts an array into a List.
Method:
static <T> List asList(T... array)
Example:
■ import [Link].*;
public class Example {
public static void main(String[] args) {
String[] arr = {"Java", "Python", "C++"};
List<String> list = [Link](arr);
[Link](list);
}
}
binarySearch( ) – Search an Element
This method searches an element in a sorted array using Binary Search.
Example:
import [Link];

public class Example {


public static void main(String[] args) {

int arr[] = {10,20,30,40,50};

int index = [Link](arr,30);

[Link]("Element found at index: " + index);


} }
Output
■ Element found at index: 2
copyOf( ) – Copy an Array
This method creates a copy of an array.
Example
int arr[] = {1,2,3,4};

int newArr[] = [Link](arr,6);

[Link]([Link](newArr));

Output
■ 1, 2, 3, 4, 0, 0
copyOfRange( ) – Copy Part of Array
Copies a specific range of elements.
Example
int arr[] = {10,20,30,40,50};

int newArr[] = [Link](arr,1,4);

[Link]([Link](newArr));
Some other Methods in Arrays
• equals( ) – Compare Two Arrays
• fill( ) – Fill Array with One Value

• mismatch( )
Finds the first position where arrays differ.

Example
Array1 = [1,2,3]
Array2 = [1,5,3]

Outupt:
1
Legacy Classes and Interfaces in Java

■ In the Java Collections Framework, the term Legacy Classes means old
classes that were used before the Collections Framework was introduced.
So Java provided some separate classes to store and manage objects.
These older classes are called Legacy Classes.
Examples of legacy classes:
• Vector
• Stack
• Hashtable
• Dictionary
• Enumeration
In Java 1.2, Java introduced the Collections Framework.
New and better classes were added, such as:
• ArrayList
• HashMap
• HashSet
These modern classes are:
• easier to use
• faster
• more flexible
What happened to old classes?
Java did not remove the old classes because old programs were still using
them.
Instead:
• They were modified to work with the Collections Framework
• So they still exist but are called legacy classes
Vector
What is Vector?
Vector is a class in Java that stores a group of objects in a dynamic array.
• Dynamic array means the size can increase automatically when more
elements are added.
• It is similar to ArrayList, but there are some differences.
Vector Declaration
class Vector<E>
• E represents the type of elements stored
Example:
Vector<Integer> v = new Vector<Integer>();
■ This means the vector will store Integer objects.
Example Program using Vector
import [Link].*;

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

Vector<String> v = new Vector<>( );

[Link]("Apple");
[Link]("Banana");
[Link]("Mango");

[Link]("First Element: " + [Link]());


[Link]("Last Element: " + [Link]());
}
}
Stack
A Stack is a class in Java that stores elements using the LIFO principle.
■ LIFO = Last In First Out
Stack is a subclass of Vector.
That means:
• Stack inherits all methods of Vector
• It also has its own special stack methods
Declaration:
class Stack<E>
Where:
• E = type of element stored
Important Stack Methods
push() Adds an element to the top of the stack.
pop() Removes and returns the top element.
peek() Returns the top element without removing it.
search() Checks if an element exists in the stack.
Exception in Stack
If you call:
• pop()
• peek()
on an empty stack, Java throws:
■ EmptyStackException
Example Program on Stack
import [Link].*;
class StackDemo {
public static void main(String args[]) {

Stack<Integer> st = new Stack<>();

[Link](10);
[Link](20);
[Link](30);
[Link]("Top element: " + [Link]());
[Link]("Removed: " + [Link]());
[Link]("Removed: " + [Link]());
}
}
Parting Thoughts on Collections
End of Module-01

You might also like