0% found this document useful (0 votes)
8 views145 pages

Lecture Slide - Week 6

The document provides an overview of nested classes and anonymous classes in Java, explaining their definitions, uses, and syntax. It details the differences between static nested classes, inner classes, and local inner classes, along with examples of each type. Additionally, it covers Java packages, their advantages, and naming conventions, emphasizing the organization and accessibility of classes within packages.

Uploaded by

guptanaman1006
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)
8 views145 pages

Lecture Slide - Week 6

The document provides an overview of nested classes and anonymous classes in Java, explaining their definitions, uses, and syntax. It details the differences between static nested classes, inner classes, and local inner classes, along with examples of each type. Additionally, it covers Java packages, their advantages, and naming conventions, emphasizing the organization and accessibility of classes within packages.

Uploaded by

guptanaman1006
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
You are on page 1/ 145

OBJECT ORIENTED

PROGRAMMING
USING JAVA
OUTLINE  Nested Classes and
Anonymous Classes
Nested Classes in java
▪ In Java, it is possible to define a class within another class, such
classes are known as nested classes. They enable you to logically
group classes that are only used in one place, thus this increases
the use of encapsulation, and creates more readable and
maintainable code.
▪ A nested class has access to the members, including private
members, of the class in which it is nested. However, the reverse is
not true i.e., the enclosing class does not have access to the
members of the nested class.
▪ A nested class is also a member of its enclosing class.
▪ As a member of its enclosing class, a nested class can be declared
private, public, protected, or package private(default).
Why Use Nested Classes?
• Logical grouping of classes—If a class is useful to only one other
class, then it is logical to embed it in that class and keep the two
together.

• Increased encapsulation—Consider two top-level classes, A and B,


where B needs access to members of A that would otherwise be
declared private. By hiding class B within class A, A's members can
be declared private and B can access them. In addition, B itself can
be hidden from the outside world.

• More readable, maintainable code—Nesting small classes within


top-level classes places the code closer to where it is used.
Nested classes are divided into two categories:
static nested class :
Nested classes that are declared static are called static nested classes.
inner class :
An inner class is a non-static nested class.
Syntax:

class OuterClass
{
...
class NestedClass
{
...
}
}
Static Nested Classes
• A static nested class is associated with its outer class similar to class
methods and variables.

• A static nested class cannot refer directly to instance variables or


methods defined in its enclosing class.

• It can use them only through an object reference.

• Static nested classes are accessed using the enclosing class name:
OuterClass.StaticNestedClass

• For example, to create an object for the static nested class, use this
syntax:
OuterClass.StaticNestedClass nestedObject =
new OuterClass.StaticNestedClass();
// a static nested class
// outer class
public class StaticNestedClassDemo
class OuterClass {
{ public static void main(String[] args)
{
static int outer_x = 10; OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();
int outer_y = 20;
private static int outer_private = 30; nestedObject.display();
static class StaticNestedClass }
{ }
void display()
{
// can access static member of outer class
System.out.println("outer_x = " + outer_x);

// can access display private static member of outer class


System.out.println("outer_private = " + outer_private);

// The following statement will give compilation error


// as static nested class cannot directly access non-static members
// System.out.println("outer_y = " + outer_y);

}
}
}
Inner Classes(Non-static nested classes)
• An inner class is associated with an instance of its enclosing class
and has direct access to that object's methods and fields.

• Because an inner class is associated with an instance, it cannot


define any static members itself.

• Objects that are instances of an inner class exist within an instance


of the outer class.
• Consider the following classes:
class OuterClass {
...
class InnerClass { ... }
}
• An instance of InnerClass can exist only within an instance of OuterClass
and has direct access to the methods and fields of its enclosing instance.

• To instantiate an inner class, we must first instantiate the outer class. Then,
create the inner object within the outer object.

• Syntax:
OuterClass.InnerClass innerObject =
outerObject.new InnerClass();

• Non-static nested classes(or inner classes comes in three variations):


➢ Member inner classes(A class created within class and outside method.)
➢ Local inner classes(A class created inside method/or inside any block)
➢ Anonymous classes (also called anonymous inner classes)[class with
no name]
Example 1
// Java program to demonstrate accessing a member
inner class // Driver class
public class InnerClassDemo
class OuterClass {
{ public static void main(String[] args)
static int outer_x = 10; {
int outer_y = 20; OuterClass outerObject = new OuterClass();
private int outer_private = 30; OuterClass.InnerClass innerObject =
class InnerClass outerObject.new InnerClass();
{ innerObject.display();
void display()
{ }
System.out.println("outer_x = " + outer_x); }
System.out.println("outer_y = " + outer_y);
System.out.println("outer_private = " + outer_private);

}
}
}
Example 2
class TestMemberOuter1{
private int data=30;
class Inner{
void msg(){System.out.println("data is "+data);}
}

void display(){
Inner in=new Inner();
in.msg();
}
public static void main(String args[]){
TestMemberOuter1 obj=new TestMemberOuter1();
obj.display();
}
}
Local Inner Classes
• Local classes are classes that are defined in a block, which is a group of
zero or more statements between balanced braces.
For example, we can define a local class in a method body, a for loop, or an
if clause.
• A local class has access to the members of its enclosing class.
• The scope of local inner class is restricted to the block they are defined in.
• Local inner class cannot be instantiated from outside the block where it is
created in.
• Till JDK 7,Local inner class can access only final local variable of the
enclosing block. However From JDK 8, it is possible to access the non-final
local variable of enclosing block in local inner class.
More points of Local Inner Class
• A local class has access to the members of its enclosing class.
• Local inner classes can extend an abstract class or can also
implement an interface.
• Local inner could be abstract in nature also
• Local inner classes cannot be provided any access modifier
like: private, public or protected
What happens at compile time?
When a program containing a local inner class is compiled, the compiler generate
two .class files, one for the outer class and the other for the inner class that has
the reference to the outer class. The two files are named by compiler as:
Outer.class
Outer$1Inner.class
Example of Local class(Defined inside method)
class abc public class Main
{
{
int a=12,b=34;
void calculate() public static void main(String[] args)
{ {
class def
abc ob = new abc();
{
int sumCalculate() ob.calculate();
{ }
return (a+b);
}
}
int mulCalculate()
{
return (a*b);
}
}
def ob=new def();
System.out.println("Sum is "+ ob.sumCalculate());
System.out.println("Mul is "+ ob.mulCalculate());
}
}
The inner class cannot be declared as static. Inner classes are associated with the block
they are defined within and not with the external class(Outer in this case).
Java code to demonstrate the scope of inner class
public class Outer
{ private void myMethod()
{
class Inner
{
private void innerMethod()
{
System.out.println("Inside inner class");
}
}
}
public static void main(String[] args)
{
Outer outer = new Outer();
Inner inner = new Inner();
inner.innerMethod();
}
}
The above program causes compilation error because the scope of inner classes are restricted to the block they
are defined in.
Anonymous Classes
• Anonymous classes enable us to declare and instantiate a class
at the same time.
• They are like local classes except that they do not have a
name.
• The anonymous class expression consists of the following:
1. The new operator
2. The name of an interface to implement or a class to extend.
3. Parentheses that contain the arguments to a constructor, just like
a normal class instance creation expression.
4. A body, which is a class declaration body. More specifically, in
the body, method declarations are allowed but statements are not.
➢ Anonymous classes have the same access to local variables of the enclosing
scope as local classes:
• An anonymous class has access to the members of its enclosing class.

➢ Anonymous classes also have the same restrictions as local classes with
respect to their members:
• We cannot declare static initializers or member interfaces in an anonymous class.
• An anonymous class can have static members provided that they are constant
variables.

➢ Note that we can declare the following in anonymous classes:


• Fields
• Extra methods (even if they do not implement any methods of the supertype)
• Local classes
• We cannot declare constructors in an anonymous class.
Note:

When we compile a nested class, two different class files will


be created with names

Outerclass.class
Outerclass$Nestedclass.class

• Local Class is named as Outerclass$1Localclass.class


• Anonymous class is named as Outerclass$1.class
Syntax: The syntax of an anonymous class expression is like the invocation of a constructor,
except that there is a class definition contained in a block of code.

// Test can be interface,abstract/concrete class


Test t = new Test()
{
// data members and methods
public void test_method()
{
........
........
}
};
Program to understand the need of anonymous class.
//Java program to demonstrate need for Anonymous Inner class
interface Age
{
int x = 21;
void getAge();
}
class AnonymousDemo
{
public static void main(String[] args)
{
// Myclass is implementation class of Age interface
MyClass obj=new MyClass();

// calling getage() method implemented at Myclass


obj.getAge();
}
}

// Myclass implement the methods of Age Interface


class MyClass implements Age
{
@Override
public void getAge()
{
// printing the age
System.out.print("Age is "+x);
}
}
In the program, interface Age is created with getAge() method and x=21.
Myclass is written as implementation class of Age interface. As done in
Program, there is no need to write a separate class Myclass. Instead,
directly copy the code of Myclass into this parameter, as shown here:

Age oj1 = new Age() {


@Override
public void getAge() {
System.out.print("Age is "+x);
}
};
//Java program to demonstrate Anonymous inner class
interface Age
{
int x = 21;
void getAge();
}
class AnonymousDemo
{
public static void main(String[] args) {
Age oj1 = new Age() {
@Override
public void getAge() {
// printing age
System.out.print("Age is "+x);
}
};
oj1.getAge();
}
}
Types of anonymous inner class
Based on declaration and behavior, there are 3 types of
anonymous Inner classes:
1. Anonymous Inner class that extends a class :
We can have an anonymous inner class that extends a class.
class A
{
int x=12;
void show()
{
System.out.println("Hello World");
}
}

class Main
{
public static void main(String[] args)
{
A ob = new A() // annoymous inner class
{
void show()
{
System.out.println("Overridden " +x);
}
};
ob.show();
}
}
2. Anonymous Inner class that implements an interface
We can also have an anonymous inner class that implements an interface
interface A
{
int x=12;
void show();
}

class Main
{
public static void main(String[] args)
{
A ob = new A() // annoymous inner class
{
public void show()
{
System.out.println("Overridden " +x);
}
};
ob.show();
}
}
3. Anonymous class that extends abstract class
abstract class Example
{
abstract void display();
}
class Main
{
public static void main(String[] args)
{
Example ref = new Example() // annoymous inner class
{
void display(){ System.out.print("Hello"); }
};
ref.display();
}
}
Comparison between normal or regular class and static nested class
S.NO Normal/Regular inner class Static nested class

Without an outer class object Without an outer class object


existing, there cannot be an existing, there may be a static
inner class object. That is, the nested class object. That is,
inner class object is always static nested class object is not
associated with the outer class associated with the outer class
object. object.

Inside normal/regular inner


Inside static nested class, static
class, static members can’t be
members can be declared.
declared.

Both static and non static


Only a static member of outer
members of outer class can be
class can be accessed directly.
accessed directly.
Difference between Normal/Regular class and Anonymous Inner class:

➢ A normal class can implement any number of interfaces but


anonymous inner class can implement only one interface at a time.
➢ A regular class can extend a class and implement any number of
interface simultaneously. But anonymous Inner class can extend a
class or can implement an interface but not both at a time.
➢ For regular/normal class, we can write any number of constructors
but we cant write any constructor for anonymous Inner class
because anonymous class does not have any name and while
defining constructor class name and constructor name must be
same.
OUTLINE  PACKAGES IN JAVA
PACKAGES IN JAVA

• A java package is a group of similar types of classes, interfaces and


sub-packages.
• Think of it as a folder in a file directory.
• Package in java can be categorized in two form, built-in package and
user-defined package.
• There are many built-in packages such as java, lang, awt, javax,
swing, net, io, util, sql etc.
Banking Application

ACCOUNTS (PACKAGE) TRANSACTION(PACKAGE) LOAN(PACKAGE)


.CLASS FILE .CLASS FILE .CLASS FILE

.CLASS FILE .CLASS FILE .CLASS FILE


ADVANTAGE OF JAVA PACKAGE

• The classes contained in the packages of the other programs can be


easily reused.
• Java package is used to categorize the classes and interfaces so that
they can be easily maintained.
• Java package provides access protection.
• Java package removes naming collision.
PACKAGE : EXAMPLE
HIERARCHICAL REPRESENTATION OF JAVA.AWT PACKAGE
java
Package Containing awt package
awt

Color
Package Containing classes
Graphics

Font

Classes Containing methods


Image
CREATING PACKAGE: EXAMPLE

//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to
• NOTE: If no package is specified, the classes in the file
package");
goes into a special unnamed package (the same unnamed
} package for all files).
}
HOW DOESTHE JAVA RUN-TIME SYSTEM KNOWWHERETO
LOOK FOR PACKAGESTHATYOU CREATE?

 First, by default, the Java run-time system uses the current working
directory as its starting point. Thus, if your package is in a subdirectory of
the current directory, it will be found.
 Second, you can specify a directory path or paths by setting the
CLASSPATH environmental variable.
 Third, you can use the-classpath option with java and javac to specify the
path to your classes.
PREDICT THE OUTPUT?
PREDICT THE OUTPUT?

Note:Only one package is valid in java,more than one package in a single source code invalid in
java
NAMING CONVENTIONS

• Package can be named using standard java naming rule. Where it


begins with lowercase letters. This makes easy to distinguish
between package names and class name.
• Example:
• double y= java.lang.Math.sqrt();
Package class method
name name name
SEQUENCE OF THE PROGRAM:

• Note: If you import a package, all the classes and interface of that
package will be imported excluding the classes and interfaces of the
subpackages. Hence, you need to import the subpackage as well.
PREDICT THE OUTPUT?
PREDICT THE OUTPUT?
HOW TO ACCESS PACKAGE FROM ANOTHER PACKAGE?

There are three ways to access the package from outside the package.

Implicit class import:- import package.*;


Explicit class import:- import package.classname; (improves readability of code)
Fully qualified name.

Note: after package name use .*


after class name use ;
WHICH IS CORRECT?

1. import java.util.Scanner;
2. import java.util. Scanner.*;
3. import java.util.*;
4. import java.util;
WHICH IS CORRECT?

1. import java.util. Scanner;(Correct)


2. import java.util. Scanner.*;(Wrong)
3. import java.util.*;(correct)
4. import java.util;(wrong)
USING PACKAGENAME.*

1. If you use package.* then all the classes and interfaces of this
package will be accessible but not sub-packages.
2. The import keyword is used to make the classes and interface of
another package accessible to the current package.
//save byA.java EXAMPLE
package pack;
public class A{
public void msg()
{System.out.println("Hello");}
Output:
} HELLO
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
USING PACKAGENAME.CLASSNAME
If you import package.classname then only declared class of this package will be accessible.
//save byA.java

package pack;
public classA{
public void msg(){System.out.println("Hello");
}
}
Output:Hello
//save by B.java
package mypack;
import pack.A;

class B{
public static void main(String args[]){
A obj = newA();
obj.msg();
}
}
USING FULLY QUALIFIED NAME

• If you use fully qualified name then only declared class of this package will be
accessible. Now there is no need to import. But you need to use fully qualified name
every time when you are accessing the class or interface.

• It is generally used when two packages have same class name e.g. java.util and
java.sql packages contain Date class.
//save by A.java EXAMPLE:
package pack;
public class A{
public void msg(){System.out.println("Hello");}
Output:Hello

}
//save by B.java package mypack; class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name obj.msg();
}
}
EXAMPLE:

class test
{
Public static void main(string[] args)
Note:
{
• Problem with readability
Java.util.Arraylist l=new • Increase length code
java.util.ArrayList();
• Solve this problem using import statement. It is no
} required to use fully qualified name we can use short name
directly.
}
EXAMPLE:
EXAMPLE:
MULTIPLE PACKAGE SCENARIO:

• In that scenario:
• Highest priority will go to explicit class import
• Next level will goes to classes present in current working directory (default
package)
• Implicit class import
EXAMPLE:

Gives priority to explicit


import

This code executes fine


WHICH ONE ISVALID?? (IMPORTINGA PACKAGETO USE PATTERN
CLASS IN PROGRAM)

• Java-> util-> regrex-> pattern

1. Import java.*;
2. Import java.util.*;
3. Import java.util.regex.*;
4. No import required
WHICH ONE ISVALID?? (IMPORTINGA PACKAGETO USE PATTERN
CLASS IN PROGRAM)

• Java-> util-> regrex-> pattern

1. Import java.*;
2. Import java.util.*;
3. Import java.util.regex.*;
4. No import required
DEFAULT:PACKAGESAVAILABLE IN JAVA

• Java.lang package is by default package available in all java program


hence we don’t need to write import.

class example
{
public static void main (String[] Args)
String s= new String(“main”);
}
}
STATIC IMPORT
• According to sun: usage of static import reduces code improves readability
• But according to www expert (like us): usage of static import creates
confusion and reduces readability
• Hence if there is not specific requirement it is not recommended to use
static import.
• for static import:
• Explicit (import static packagename.classname.staticmember
example import static java.lang.math.sqrt;
• Implicit (import static package name .classname.*)
example:import static java.lang.math.*;
EXAMPLE
Without static import With static import
EXAMPLE
With static import
EXAMPLE

Class system (present in java lang)


{
Static printstream out; // (out is a static variable present in system class of the type print stream)
}

System.out.println() //(print is method present in the system class)


EXAMPLE
WHICH PACKAGE ISVALID?

• import java.lang.Math.*;
• import static java.lang.Math.*;
• import java.lang.Math.sqrt*;
• import static java.lang.Math.sqrt();
• import java.lang.Math.sqrt;
• import static java.lang.Math.*;
• import java.lang;
• import static java.lang;
• import java.lang.*;
• import static java.lang.*;
WHICH PACKAGE IS VALID?

• import java.lang.Math.*; (invalid after class ; not star)


• import static java.lang.Math.*;(valid)
• import java.lang.Math.sqrt*; (invalid : will take, till class level not till
data member)
• import static java.lang.Math.sqrt(); (invalid not bracket open or close)
• import java.lang.Math.sqrt; (invalid)
• import static java.lang.Math.*;(valid)
• import java.lang; (invalid .* required)
• import static java.lang; (invalid always talks about class and data
member)
• import java.lang.*; (valid)
• import static java.lang.*;(invalid)
FINAL
• It is the modifier applicable for classes, methods and variables.
• If a method declared as the final then we are not allowed to override that method in the child
class.
• Whatever the methods parent has by default available to the child.
Methods • If the child is not allowed to override any method,that method we have to declare with
final in parent class.That is final methods cannot overridden.

• If a class declared as the final then we can't creates the child class that is
Class
inheritance concept is not applicable for final classes.

• If a variable declared as the final then we need to look for the type of variables
Variables
and then correspondingly actions need to be taken (discussed later in the slides).
EXAMPLE
final class Test
{
void methodOne( )
{
System.out.println(“Protected Member Access
Modifier”);
}
}
class public static void main(String args[])
Test1 {
extends Test t=newTest();
Every method present inside a final class is always final Test t.methodOne();
{ Test1 b = newTest1();
by default whether we are declaring or not. But every b.methodOne();
variable present inside a final class need not be final. Test c = newTest1();
c.methodOne();
}
}
FINAL VARIABLES IN INSTANCE VARIABLES

• If the value of a variable is varied from object to object such type of variables are
called instance variables.
• For every object a separate copy of instance variables will be created.

• For the instance variables it is not required to perform initialization explicitly jvm will
always provide default values.
FINAL VARIABLES IN INSTANCE VARIABLES

• If the instance variable declared as the final compulsory we should perform


initialization explicitly and JVM won't provide any default values. whether we are
using or not otherwise we will get compile time error.
classTest classTest
{ {
int i; final int i;
} }

• For the final instance variables we should perform initialization before constructor
completion. That is the following are various possible places for this.
• Initialization while declaration, instance initialization block, and constructor.
FINAL VARIABLES IN STATIC VARIABLES

• If the static variable declare as final then compulsory we should perform initialization
explicitly whether we are using or not otherwise we will get compile time error.(The
JVM won't provide any default values)

• For the final static variables we should perform initialization before class loading
completion otherwise we will get compile time error. That is the following are
possible places.
• Initialization while declaration and inside static block.
FINAL VARIABLES IN LOCAL VARIABLES

• To meet temporary requirement of the Programmer sometime we can declare the


variable inside a method or block or constructor such type of variables are called local
variables.
• For the local variables jvm won't provide any default value compulsory we should
perform initialization explicitly before using that variable.
• The only applicable modifier for local variables is final if we are using any other
modifier we will get compile time error.
classTest
{
public static void main(String [] args) {
final int i;
System.out.println(“Bennett”);
}
}
FINAL VARIABLES IN LOCAL VARIABLES
Java Collections

77
Java 2 Collections
• A collection is an object that groups multiple
elements into a single unit
• Very useful
» store, retrieve and manipulate data
» transmit data from one method to another
» data structures and methods written by hotshots in the field
• Joshua Bloch, who also wrote the Collections tutorial
Collections Framework
• Unified architecture for representing and manipulating collections.
• A collections framework contains three things
» Interfaces
» Implementations
» Algorithms

79
Collections Framework Diagram

80
Collection Interface
• Defines fundamental methods
» int size();
» boolean isEmpty();
» boolean contains(Object element);
» boolean add(Object element); // Optional
» boolean remove(Object element); // Optional
» Iterator iterator();

• These methods are enough to define the basic behavior of a collection


• Provides an Iterator to step through the elements in the Collection

81
Example - SimpleCollection
public class SimpleCollection {
public static void main(String[] args) {
Collection c;
c = new ArrayList();
System.out.println(c.getClass().getName());
for (int i=1; i <= 10; i++) {
c.add(i + " * " + i + " = "+i*i);
}
Iterator iter = c.iterator();
while (iter.hasNext())
System.out.println(iter.next());
}
}

82
List Interface Context

Collection

List

83
List Interface
• The List interface adds the notion of order to a collection
• The user of a list has control over where an element is added in the
collection
• Lists typically allow duplicate elements
• Provides a ListIterator to step through the elements in the list.

84
ListIterator Interface
• Extends the Iterator interface
• Defines three fundamental methods
» void add(Object o) - before current position
» boolean hasPrevious()
» Object previous()

• The addition of these three methods defines the basic behavior of an


ordered list
• A ListIterator knows position within list

85
ArrayList and LinkedList Context

Collection

List

ArrayList LinkedList

86
List Implementations
• ArrayList
» low cost random access
» high cost insert and delete
» array that resizes if need be
• LinkedList
» sequential access
» low cost insert and delete
» high cost random access

87
ArrayList

1. An ArrayList is one of the resizable list implementaions of the generic list interface, the other being
Vector Class.
2. Each ArrayList object has a capacity. The capacity is the size of the array used to store the elements
in the list and it is as large as the list size. As the elements are added into the list, its capacity grows
automatically.
3. The ArrayList concept provides the facility by creating an array of some default size. If it becomes
insufficient to add more elements into this initial array then system creates a new larger array and
copies the content of previous array into the new array and remaining space in new array for adding
additional elements and this process keeps happening but programmer is not aware of this activity.

88
ArrayList Continued
4. An ArrayList object can only store references of Java Class objects and variables of primitive types
such as int, float, double etc. can not be stored in an ArrayList.

5. An ArrayList object in not synchronized i.e multiple independent threads can access a particular
ArrayList object simultaneously.

3-February-2003 cse403-10-Collections © 2003 University of Washington 89


ArrayList overview
• Constant time positional access (it’s an array)
• One tuning parameter, the initial capacity

public ArrayList(int initialCapacity) {


super();
if (initialCapacity < 0)
throw new IllegalArgumentException(
"Illegal Capacity: "+initialCapacity);
this.elementData = new Object[initialCapacity];
}
Some of the frequently used ArrayList Class Methods

1) boolean add(E e): Append a specified element e to the end of the concerned
ArrayList object.
2) void add(int index, E element): Inserts the speicified element at the specified
position in the concerned ArrayList.
3) int capacity(): returns the current capacity of the concerned ArrayList object.
4) void clear(): removes all of the elements from the concerned ArrayList object.
5) boolean contains(Object O): returns true if the concerned ArrayList object holds
the reference of Object O passed as argument.
6) Iterator<E> interator: returns an iterator object to iterate over the elements of the
concerned ArrayList object.
7) E set(int index, E element): Replaces the element at specified position in the list
with specified element
8) int indexOf(Object O): returns the index of first occurrence of element O in
concerned ArrayList.
92
93
94
95
Vector Class
▪ Like ArrayList, Vector generic class provides you a mechanism to implement a
growable list of objects by initially creating a default size array and by creating new
larger size arrays according to requirement similar to ArrayList
▪ Elements can be accessed using index.
▪ Each Vector Class object optimize storage management by maintaining two
parameters capacity, and capacityIncrement. The capacity is always as larger as size
of Vector object. Once the objects are added into Vector, the vector storage
increases in chunks the size of capacityIncrement.
▪ Like ArrayList, this class objects also provide iterator object to traverse its elements
in a sequence.
▪ The main difference between an ArrayList and Vector Class objects is that Vector
Class objects are thread safe i.e. at a particular instant only a single thread can
modify a particular Vector Class object but this not with an ArrayList object.
▪ Most of the utility methods calls in ArrayList and Vector Classes are same.

96
Some of the frequently Vector Class Methods

1) boolean add(E e): Append a specified element e to the end of the concerned Vector
object.
2) void add(int index, E element): Inserts the speicified element at the specified
position in the concerned Vector.
3) int capacity(): returns the current capacity of the concerned Vector object.
4) void clear(): removes all of the elements from the concerned Vector object.
5) boolean contains(Object O): returns true if the concerned Vector object holds the
reference of Object O passed as argument.
6) Iterator<E> interator: returns an iterator object to iterate over the elements of the
concerned Vector object.
7) int indexOf(Object O): returns the index of first occurrence of element O in
concerned ArrayList.
8) E set(int index, E e): replaces the element at specified index position with the
specified element.
98
Stack Class in Java
1) The Stack class represents a last in first out(LIFO) stack of objects.
2) It extends the Vector Class with five operations that allow a Vector to be
treated as a stack.
3) Those five additional operations are mentioned below
4) E peek(): determines the element at the top of stack without removing it.
5) E pop(): removes the object at the top of this stack and returns the value
of this function
6) E push(E item): pushes an item at the top of this stack.

99
100
101
102
PriorityQueue
1) It is a collection in which elements are ordered according to their natural
ordering, or by a comparator provided at Queue construction time
depending upon type of constructor used.
2) The head of this queue is the least element with specified ordering.
3) A priority queue is unbounded, but has an internal capacity governing the
size of the array used to store the elements on the queue.
4) As elements are added into queue it’s capacity grows automatically.
5) The implementation of PriorityQueue is not synchronized there multiple
thread instances shold not access a PriorityQueue instance concurrently
Some most frequently used priority queue methods

1) boolean add(E e): Inserts the specified element in the priority queue.
2) comparator(): Returns the comparator used to order elements in this queue or null is returned if natural
ordering is used.
3) boolean contains(Object O): Returns true if the queue contains the specified element.
4) boolean offer(E e): returns true if the queue contains the specified element.
5) poll(): retrieves and removes the head of this queue or returns null if queue is empty
6) remove(Object O): removes a single instance of the specified element from this queue of null is
returned if queue is empty.
7) Int size(): Size of queue is returned

104
LinkedList overview
• Stores each element in a node
• Each node stores a link to the next and previous nodes
• Insertion and removal are inexpensive
» just update the links in the surrounding nodes
• Linear traversal is inexpensive
• Random access is expensive
» Start from beginning or end and traverse each node while counting

107
LinkedList entries
private static class Entry {
Object element;
Entry next;
Entry previous;

Entry(Object element, Entry next, Entry previous) {


this.element = element;
this.next = next;
this.previous = previous;
}
}

private Entry header = new Entry(null, null, null);

public LinkedList() {
header.next = header.previous = header;
}
108
Some frequently used linked list methods

1) add(E e): The specified element e is appended at the end of the linked list.
2) add(int position, E element): the specified element is inserted at the specified position in the linked
list.
3) contains(Object o): returns true if object o is present in the linked list.
4) get(int position): returns the element at the specified position in the list
5) peek(): retrieves but does not removes the first element of the linked list
6) Remove(): retrieves and then removes the first element of the linked list
7) remove(int position): removes the element present at the specified position in the linked list.
8) set(int position, E e): replaces the element present at the specified position with element e.

109
110
111
112
Set Interface Context

Collection

Set

113
Set Interface
• Same methods as Collection
» different contract - no duplicate entries
• Defines two fundamental methods
» boolean add(Object o) - reject duplicates
» Iterator iterator()
• Provides an Iterator to step through the elements
in the Set
» No guaranteed order in the basic Set interface
» There is a SortedSet interface that extends Set

114
HashSet and TreeSet Context

Collection

Set

HashSet TreeSet

115
HashSet
• Find and add elements very quickly
» uses hashing implementation in HashMap
• Hashing uses an array of linked lists
» The hashCode() is used to index into the array
» Then equals() is used to determine if element is in the
(short) list of elements at that index
• No order imposed on elements
• The hashCode() method and the equals() method
must be compatible
» if two objects are equal, they must have the same
hashCode() value
116
Some most frequently used HashSet methods

1)boolean add(E e): The specified element e is added into the concerned HashSet when the element is not
alerady present.
2) Void clear(): All elements are removed from the concerned HashSet.
3) boolean contains(Object O): returns true if the concerned HashSet contains the specified element.
4) boolean isEmpty(): returns true if the concerned HashSet contains no element.
5) boolean remove(Object O): removes the specified element from the concerned HashSet.
6)int size(): returns the size of the concerned HashSet.

117
118
119
120
TreeSet
• Elements can be inserted in any order
• The TreeSet stores them in order
» Red-Black Trees out of Cormen-Leiserson-Rivest
• An iterator always presents them in order
• Default order is defined by natural order
» objects implement the Comparable interface
» TreeSet uses compareTo(Object o) to sort
• Can use a different Comparator
» provide Comparator to the TreeSet constructor

121
Some most frequently used TreeSet methods

1)boolean add(E e): The specified element e is added into the concerned TreeSet when the element is not
alerady present.
2) Void clear(): All elements are removed from the concerned TreeSet.
3) boolean contains(Object O): returns true if the concerned TreeSet contains the specified element.
4) boolean isEmpty(): returns true if the concerned TreeSet contains no element.
5) boolean remove(Object O): removes the specified element from the concerned TreeSet.
6)int size(): returns the size of the concerned HashSet.
7) E higher(E e): returns the least element in the concerned TreeSet strictly greater than specified element
or null if there is no such element.

122
123
124
125
Linked Hash Set

• It’s a direct descendant of the HashSet data structure, hence, contains


non-duplicate elements at every given time.
• LinkedHashSet maintains a linked list of the entries in the set, in the
order in which they were inserted. This allows insertion-order iteration
over the set.
• That is, when cycling through a LinkedHashSet using an iterator, the
elements will be returned in the order in which they were inserted.

126
Some most frequently used LinkedHashSet methods

1)boolean add(E e): The specified element e is added into the concerned LinkedHashSet when the
element is not alerady present.
2) Void clear(): All elements are removed from the concerned LinkedHashSet.
3) boolean contains(Object O): returns true if the concerned LinkedHashSet contains the specified
element.
4) boolean isEmpty(): returns true if the concerned LinkedHashSet contains no element.
5) boolean remove(Object O): removes the specified element from the concerned LinkedHashSet.
6)int size(): returns the size of the concerned LinkedHashSet.

127
128
129
130
Map Interface Context

Map

131
Map Interface
• Stores key/value pairs
• Maps from the key to the value
• Keys are unique
» a single key only appears once in the Map
» a key can map to only one value
• Values do not have to be unique

132
HashMap
1)A HashMap is a implementation of Map interface and conceptually its
similar to a Hashtable thus providing a key,value pair type recording of
information.
2)A hashmap is created using following statement:
HashMap<K,V> Map1=new HashMap<K,V> where K may be any valid class
a class for key objects and V may be any class for value objects. E.g
HashMap<String,Integer> Map1=new HashMap<String,Integer> ();

2) This implementation provides a constant time performance of the basic


operations(get and put functions).
3) An instance of Hashmap has two parameters that affect its performance.
Initial capacity and load factor. The capacity is the number of buckets in the
hashtable and load factor is a measure of how full the hashmap is allowed to
get before its capacity is increased.
4) A Hashmap based collection is not thread synchronized
Some frequently used HashMap methods

1)boolean containsKey(Object k): Returns true if concerned HashMap contains


a mappting corresponding to Key k.

2) boolean containsValue(Object v): returns true is concerned HashMap


contains atleast one key,value mapping in which value is v.

3) V get(Object k): returns the value to which specified key k is mapped or


null is returned if there is no mapping for key k.

4)V put(key k, value v): Associates the specified value v with specified key in
the HashMap.
5) V remove(Object k): the mapping based on specified key k is removed from
the HashMap.
6) V replace(Key k, Value v): the entry based on key k is replaced if it is
already present in HashMap.
134
135
136
TreeMap
1) A TreeMap is also a key,value mapping based collection for information
storage.

2) A TreeMap collection is collected using following Statement

3) TreeMap<Key,Value> Map1=new TreeMap<Key,Value>();

4) Conceptually it’s implementation is based on a red black tree thus


elements are arranged according to their natural ordering.

5) Like HashMap, the implementation of a TreeMap object is not thread


Synchronized.
Some of the frequently used TreeMap Methods

1) ceilingEntry(Key k): returns a key,value pair based entry associated with least key greater than or
equal to the given Key k or null is returned.
2) ceilingKey(Key k): returns a key greater than or equal to the given Key k or null is returned.
3) containsKey(Object k): true is returned if there is mapping in TreeMap containing Key k.
4) containsValue(Object v): true is returned if there is atleast one mapping with value v in TreeMap
5) get(Object k): the value v is returned corresponding to key k is mapping k,v is present in TreeMap
otherwise null is returned.
6) put(Key k, Value v): a mapping corresponding to Key k and Value v is recorded in TreeMap
LinkedHashMap
1) It is an implementation of Map interface based upon the concepts of
Hashtable and linkedlist.
2) This implementation is different from HashMap in that this collections
also maintains a double linkedlist consisting of all key,value pair enteries.
3) Like HashMap, it provides constant time operations.
4) Like HashMap it also allows permits null elements.
5) The implementation of LinkedHashMap is not synchronized.

141
Some frequently used LinkedHashMap Methods

1) containsValue(Object V): returns true if there is ateast one K,V mapping


present in LinkedHashMap with value V.
2) get(Object k): returns the Object reference of value v corresponding to key
k.
3) put(Object k,Object v): inserts the k,v pair in the linkedhashmap
4) remove(object k): key value pair corresponding to key k is removed from
the linkedhashmap and the value v corresponding to key k is returned.
5) replace(Key k, Value v): the current value v1 corresponding to key k is
replaced with value v is there is already an entry present corresponding to
key k.
6) size(): current size of the linkedhashmap is returned
THANK YOU

You might also like