0% found this document useful (0 votes)
12 views60 pages

Unit 4 OOPJ

The document discusses autoboxing and unboxing in Java, which are processes that convert primitive types to wrapper objects and vice versa. It explains the benefits of these processes, such as preventing errors and allowing for the interchangeability of primitive types and wrapper objects. Additionally, the document covers Java strings, their immutability, and the functionality of the StringBuffer class for mutable string operations.

Uploaded by

Divya
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)
12 views60 pages

Unit 4 OOPJ

The document discusses autoboxing and unboxing in Java, which are processes that convert primitive types to wrapper objects and vice versa. It explains the benefits of these processes, such as preventing errors and allowing for the interchangeability of primitive types and wrapper objects. Additionally, the document covers Java strings, their immutability, and the functionality of the StringBuffer class for mutable string operations.

Uploaded by

Divya
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/ 60

0 9 -1 2 -2 0 2 4

Unit4 - Autoboxing, java.lang package

Mrs. Divya M Patel (TMESICS) 1

Chapter 9- Autoboxing

Mrs. Divya M Patel (TMESICS) 2

1
0 9 -1 2 -2 0 2 4

Autoboxing (Primitive Type to Wrapper


Object)
 In Java, primitive data types are treated differently so do there comes the
introduction of wrapper classes where two components play a role namely
Autoboxing and Unboxing.
 Autoboxing refers to the conversion of a primitive value into an object of the
corresponding wrapper class. For example, converting int to Integer class.
 The Java compiler applies autoboxing when a primitive value is: Passed as a
parameter to a method that expects an object of the corresponding wrapper class.
 Assigned to a variable of the corresponding wrapper class.

Mrs. Divya M Patel (TMESICS) 3

Autoboxing (Primitive Type to Wrapper


Object)
 For example,

 Autoboxing has a great advantage


while working with Java
collections.

Mrs. Divya M Patel (TMESICS) 4

2
0 9 -1 2 -2 0 2 4

Autoboxing (Primitive Type to Wrapper


Object)
 In the above example, we have created an array list of Integer type. Hence
the array list can only hold objects of Integer type.

 Here, we are passing primitive type value. However, due to autoboxing, the
primitive value is automatically converted into an Integer object and stored
in the array list.

Mrs. Divya M Patel (TMESICS) 5

Java Unboxing (Wrapper Objects to Primitive


Types)
 In unboxing, the Java compiler automatically converts wrapper class
objects into their corresponding primitive types.
 For example,

Mrs. Divya M Patel (TMESICS) 6

3
0 9 -1 2 -2 0 2 4

Java Unboxing (Wrapper Objects to Primitive


Types)

 Here, the get() method returns


the object at index 0. However,
due to unboxing, the object is
automatically converted into
the primitive type int and
assigned to the variable a.

Mrs. Divya M Patel (TMESICS) 7

Benefits of Autoboxing / Unboxing


 Autoboxing / Unboxing lets us use primitive types and Wrapper class objects
interchangeably.
 We don't have to perform Explicit typecasting.
 It helps prevent errors, but may lead to unexpected results sometimes.
Hence must be used with care.
 Auto-unboxing also allows you to mix different types of numeric objects in an
expression. When the values are unboxed, the standard type conversions can be
applied.

Mrs. Divya M Patel (TMESICS) 8

4
0 9 -1 2 -2 0 2 4

Wrapper Class
 The wrapper
classes in Java are
used to convert
primitive types
(int, char, float,
etc) into
corresponding
objects.
 Each of the 8
primitive types
has corresponding
wrapper classes.
Mrs. Divya M Patel (TMESICS) 9

Wrapper Class
 Advantages of Wrapper Classes:
 In Java, sometimes we might need to use objects instead of primitive data
types. For example, while working with collections.

 In such cases, wrapper classes help us to use primitive data types as


objects.

Mrs. Divya M Patel (TMESICS) 1


0

5
0 9 -1 2 -2 0 2 4

Wrapper Class
 We can store the null value in wrapper objects. For example,

Mrs. Divya M Patel (TMESICS) 1


1

Wrapper Class
 Convert Primitive
Type to Wrapper
Objects.
 We can also use the
valueOf() method to
convert primitive
types into
corresponding
objects.

Mrs. Divya M Patel (TMESICS) 1


2

6
0 9 -1 2 -2 0 2 4

Wrapper Class

 In the above example, we have used the valueOf() method to convert the
primitive types into objects.
 Here, we have used the instanceof operator to check whether the generated
objects are of Integer or Double type or not.
 However, the Java compiler can directly convert the primitive types into
corresponding objects.
 This process is known as auto-boxing.
 For example,

Mrs. Divya M Patel (TMESICS) 1


3

Wrapper Class
 Wrapper Objects into Primitive Types
 To convert objects into the primitive types, we can use the corresponding
value methods (intValue(), doubleValue(), etc) present in each wrapper
class.
 In the below example, we have used the intValue() and doubleValue()
method to convert the Integer and Double objects into corresponding
primitive types.

Mrs. Divya M Patel (TMESICS) 1


4

7
0 9 -1 2 -2 0 2 4

Wrapper Class

Mrs. Divya M Patel (TMESICS) 1


5

Wrapper Class
 In the above example, we have used the intValue() and doubleValue() method
to convert the Integer and Double objects into corresponding primitive types.
 This process is known as unboxing.
 For example,

Mrs. Divya M Patel (TMESICS) 1


6

8
0 9 -1 2 -2 0 2 4

Autoboxing/Unboxing Occurs in Expressions


 In general, autoboxing and unboxing take place whenever a conversion into
an object or from an object is required.
 This applies to expressions. Within an expression, a numeric object is
automatically unboxed.
 The outcome of the expression is reboxed, if necessary.
 For example, consider the following program:

Mrs. Divya M Patel (TMESICS) 1


7

Autoboxing/Unboxing Occurs in Expressions

Mrs. Divya M Patel (TMESICS) 1


8

9
0 9 -1 2 -2 0 2 4

String
 In Java, a string is a sequence of characters. For example, "hello" is a string
containing a sequence of characters 'h', 'e', 'l', 'l', and 'o'.
 We use double quotes to represent a string in Java. For example,

 Here, we have created a string variable named type. The variable is initialized
with the string Java Programming.

Mrs. Divya M Patel (TMESICS) 1


9

String
 In this example, we have created
three strings named first, second,
and third.
Here, we are directly creating
strings like primitive types.
 However, there is another way
of creating Java strings (using
the new keyword).

Mrs. Divya M Patel (TMESICS) 2


0

10
0 9 -1 2 -2 0 2 4

String
 Java String Operations:- Java String provides various methods to perform
different operations on strings. We will look into some of the commonly
used string operations.
1. Get length of a String:- To find the length of a string, we use the length()
method of the String.
2. Join Two Java Strings:- We can join two strings in Java using the concat()
method. We can also join two strings using the + operator in Java.
3. Compare two Strings:- In Java, we can make comparisons between two
strings using the equals() method.

Mrs. Divya M Patel (TMESICS) 2


1

String
 We can also compare two strings using the == operator in Java. However, this
approach is different than the equals() method.

Mrs. Divya M Patel (TMESICS) 2


2

11
0 9 -1 2 -2 0 2 4

String

Mrs. Divya M Patel (TMESICS) 2


3

String
 Escape character in Java Strings:- The escape character is used to escape
some of the characters present inside a string.
 Suppose we need to include double quotes inside a string.

 Since strings are represented by double quotes, the compiler will treat "This is
the " as the string. Hence, the above code will cause an error.

Mrs. Divya M Patel (TMESICS) 2


4

12
0 9 -1 2 -2 0 2 4

String
 To solve this issue, we use the escape character \ in Java. For example,

 Now, escape characters tell the compiler to escape double quotes and read
the whole text.

Mrs. Divya M Patel (TMESICS) 2


5

String
 Java Strings are Immutable:- In Java, strings are immutable. This means,
once we create a string, we cannot change that string.
 To understand it more deeply, consider an example:

Mrs. Divya M Patel (TMESICS) 2


6

13
0 9 -1 2 -2 0 2 4

String
 Here, we have created a string variable named example. The variable holds the
string "Hello! ".
 Now suppose we want to change the string.

 Here, we are using the concat() method to add another string World to the
previous string.
 It looks like we are able to change the value of the previous string. However,
this is not true.

Mrs. Divya M Patel (TMESICS) 2


7

String
 Let's see what has happened here,
1. JVM takes the first string "Hello! “
2. creates a new string by adding "World" to the first string
3. assign the new string "Hello! World" to the example variable
4. the first string "Hello! " remains unchanged

Mrs. Divya M Patel (TMESICS) 2


8

14
0 9 -1 2 -2 0 2 4

String
 Creating strings using the new keyword
 So far we have created strings like primitive types in Java.
 Since strings in Java are objects, we can create strings using the new
keyword as well. For example,

 In the above example, we have created a string name using the new
keyword.
 Here, when we create a string object, the String() constructor is invoked.

Mrs. Divya M Patel (TMESICS) 2


9

Methods of Java String

Mrs. Divya M Patel (TMESICS) 3


0

15
0 9 -1 2 -2 0 2 4

Methods of Java String

Mrs. Divya M Patel (TMESICS) 3


1

Methods of Java String

Mrs. Divya M Patel (TMESICS) 3


2

16
0 9 -1 2 -2 0 2 4

String Buffer
 StringBuffer is a peer class of String that provides much of the functionality
of strings.
 The string represents fixed-length, immutable character sequences while
StringBuffer represents growable and writable character sequences.
 Java StringBuffer class is used to create mutable (modifiable) String objects.
 The StringBuffer class in Java is the same as String class except it is mutable
i.e. it can be changed.

Mrs. Divya M Patel (TMESICS) 3


3

String Buffer
 Constructors of StringBuffer class
1. StringBuffer(): It reserves room for 16 characters without reallocation.

2. StringBuffer(int size): It accepts an integer argument that explicitly sets the


size of the buffer.

3. StringBuffer(String str): It accepts a string argument that sets the initial


contents of the StringBuffer object and reserves room for 16 more characters
without reallocation.

Mrs. Divya M Patel (TMESICS) 3


4

17
0 9 -1 2 -2 0 2 4

String Buffer Methods


1. append() method:- The append() method concatenates the given argument
with this string.

Mrs. Divya M Patel (TMESICS) 3


5

String Buffer Methods


2. insert() method:- The insert() method inserts the given string with this
string at the given position.

Mrs. Divya M Patel (TMESICS) 3


6

18
0 9 -1 2 -2 0 2 4

String Buffer Methods


3. replace() method:- The replace() method replaces the given string from the
specified beginIndex and endIndex-1.

Mrs. Divya M Patel (TMESICS) 3


7

String Buffer Methods


4. delete() method:- The delete() method of StringBuffer class deletes the string
from the specified beginIndex to endIndex-1.

Mrs. Divya M Patel (TMESICS) 3


8

19
0 9 -1 2 -2 0 2 4

String Buffer Methods


5. reverse() method:- The reverse() method of StringBuilder class reverses the
current string.

Mrs. Divya M Patel (TMESICS) 3


9

String Buffer Methods


6. capacity() method:- The capacity() method of StringBuffer class returns the
current capacity of the buffer.
 The default capacity of the buffer is 16.
 If the number of character increases from its current capacity, it increases the
capacity by (oldcapacity*2)+2.
 For example if your current capacity is 16, it will be (16*2)+2=34.

Mrs. Divya M Patel (TMESICS) 4


0

20
0 9 -1 2 -2 0 2 4

String Buffer

Mrs. Divya M Patel (TMESICS) 4


1

String Buffer
 Auxiliary methods of String buffer are as follows:
 ensureCapacity(): It is used to increase the capacity of a StringBuffer
object. The new capacity will be set to either the value we specify or twice the
current capacity plus two (i.e. capacity+2), whichever is larger. Here, capacity
specifies the size of the buffer.
 Syntax:

 appendCodePoint(int codePoint): This method appends the string


representation of the codePoint argument to this sequence.
 Syntax:

Mrs. Divya M Patel (TMESICS) 4


2

21
0 9 -1 2 -2 0 2 4

String Buffer
 charAt(int index): This method returns the char value in this sequence at the
specified index.
 Syntax:

 int codePointAt(int index): This method returns the character (Unicode code
point) at the specified index.
 Syntax:

Mrs. Divya M Patel (TMESICS) 4


3

String Buffer
 int codePointBefore(int index): This method returns the character (Unicode
code point) before the specified index.
 Syntax:

 int codePointCount(int beginIndex, int endIndex): This method returns the


number of Unicode code points in the specified text range of this sequence.
 Syntax:

Mrs. Divya M Patel (TMESICS) 4


4

22
0 9 -1 2 -2 0 2 4

String Buffer
 int indexOf(String str): This method returns the index within this string of
the first occurrence of the specified substring.
 Syntax:

 int lastIndexOf(String str): This method returns the index within this string
of the last occurrence of the specified substring.
 Syntax:

Mrs. Divya M Patel (TMESICS) 4


5

Difference between String vs. String Buffer

Mrs. Divya M Patel (TMESICS) 4


6

23
0 9 -1 2 -2 0 2 4

Comparable interface
 As the name itself suggests, Comparable is an interface which defines a way
to compare an object with other objects of the same type.
 It helps to sort the objects that have self-tendency to sort themselves, i.e., the
objects must know how to order themselves. Eg: Roll number, age, salary.
 This interface is found in java.lang package and it contains only one method,
i.e., compareTo().
 Comparable is not capable of sorting the objects on its own, but the interface
defines a method int compareTo() which is responsible for sorting.

Mrs. Divya M Patel (TMESICS) 4


7

Comparable interface
 public int compareTo(Object obj): It is used to compare the current object
with the specified object.
 int compareTo(String str): Here, str is the String being compared with the
invoking String. The result of the comparison is returned and is
interpreted, as shown here:

Mrs. Divya M Patel (TMESICS) 4


8

24
0 9 -1 2 -2 0 2 4

Comparable interface
 Using Comparable Interface
 In this method, we are going to implement the Comparable interface from
java.lang Package in the Pair class.
 The Comparable interface contains the method compareTo to decide the
order of the elements.
 Override the compareTo method in the Pair class.
 Create an array of Pairs and populate the array.
 Use the Arrays.sort() function to sort the array.

Mrs. Divya M Patel (TMESICS) 4


9

Comparable interface

Mrs. Divya M Patel (TMESICS) 5


0

25
0 9 -1 2 -2 0 2 4

Comparable interface

Mrs. Divya M Patel (TMESICS) 5


1

Chapter 10- The Collection Framework

Mrs. Divya M Patel (TMESICS) 52

26
0 9 -1 2 -2 0 2 4

The collection Framework


 The Java collections framework provides a set of interfaces and classes to
implement various data structures and algorithms.
 For example, the LinkedList class of the collections framework provides the
implementation of the doubly-linked list data structure.
 Interfaces of Collections FrameWork
 The Java collection framework provides various interfaces.
 These interfaces include several methods to perform different operations on
collections.

Mrs. Divya M Patel (TMESICS) 53

The collection Framework

Mrs. Divya M Patel (TMESICS) 54

27
0 9 -1 2 -2 0 2 4

The collection Interface


 Java Collection Interface:- The Collection interface is the root interface of the
Java collections framework.
 There is no direct implementation of this interface. However, it is
implemented through its subinterfaces like List, Set, and Queue.
 For example, the ArrayList class implements the List interface which is a
subinterface of the Collection Interface.

Mrs. Divya M Patel (TMESICS) 55

The collection Interface

 Subinterfaces of Collection:- As mentioned above, the Collection interface


includes subinterfaces that are implemented by various classes in Java.

Mrs. Divya M Patel (TMESICS) 56

28
0 9 -1 2 -2 0 2 4

The collection Interface


1. List Interface:- In Java, the List interface is an ordered collection that allows
us to store and access elements sequentially.
 It extends the Collection interface.
 Classes that Implement List:- Since List is an interface, we cannot create
objects from it.
 In order to use functionalities of the List interface, we can use these classes:
 ArrayList
 LinkedList
 Vector
 Stack

Mrs. Divya M Patel (TMESICS) 57

The collection Interface


 How to use List?
 In Java, we must import java.util.List package in order to use List.

 Here, we have created objects list1 and list2 of classes ArrayList and
LinkedList. These objects can use the functionalities of the List interface.

Mrs. Divya M Patel (TMESICS) 58

29
0 9 -1 2 -2 0 2 4

The collection Interface


 Methods of List:- The List interface includes all the methods of the
Collection interface. Its because Collection is a super interface of List.
 Some of the commonly used methods of the Collection interface that's also
available in the List interface are:
 add() - adds an element to a list
 addAll() - adds all elements of one list to another
 get() - helps to randomly access elements from lists
 iterator() - returns iterator object that can be used to sequentially access elements of lists
 set() - changes elements of lists
 remove() - removes an element from the list
 removeAll() - removes all the elements from the list
 clear() - removes all the elements from the list (more efficient than removeAll())
 size() - returns the length of lists
 toArray() - converts a list into an array
 contains() - returns true if a list contains specified element
Mrs. Divya M Patel (TMESICS) 59

The collection Interface


2. Set Interface:- The Set interface of the Java Collections framework provides the
features of the mathematical set in Java.
 It extends the Collection interface.
 Unlike the List interface, sets cannot contain duplicate elements.
 Classes that implement Set:- Since Set is an interface, we cannot create
objects from it.
 In order to use functionalities of the Set interface, we can use these
classes:
 HashSet
 LinkedHashSet
 EnumSet
 TreeSet Mrs. Divya M Patel (TMESICS) 60

30
0 9 -1 2 -2 0 2 4

The collection Interface


 These classes are defined in the Collections framework and implement the Set
interface.

 Interfaces that extend Set


 The Set interface is also extended by these subinterfaces:
 SortedSet
 NavigableSet

Mrs. Divya M Patel (TMESICS) 61

The collection Interface

 How to use Set?


 In Java, we must import java.util.Set package in order to use Set.

 Here, we have created a Set called animals. We have used the HashSet class to
implement the Set interface.

Mrs. Divya M Patel (TMESICS) 62

31
0 9 -1 2 -2 0 2 4

The collection Interface


 Methods of Set:- The Set interface includes all the methods of the Collection
interface. It's because Collection is a super interface of Set.
 Some of the commonly used methods of the Collection interface that's
also available in the Set interface are:
 add() - adds the specified element to the set
 addAll() - adds all the elements of the specified collection to the set
 iterator() - returns an iterator that can be used to access elements of the set
sequentially
 remove() - removes the specified element from the set
 removeAll() - removes all the elements from the set that is present in another
specified set
Mrs. Divya M Patel (TMESICS) 63

The collection Interface


 retainAll() - retains all the elements in the set that are also present in another
specified set
 clear() - removes all the elements from the set
 size() - returns the length (number of elements) of the set
 toArray() - returns an array containing all the elements of the set
 contains() - returns true if the set contains the specified element
 containsAll() - returns true if the set contains all the elements of the specified
collection
 hashCode() - returns a hash code value (address of the element in the set)

Mrs. Divya M Patel (TMESICS) 64

32
0 9 -1 2 -2 0 2 4

The collection Interface


 Set Operations:- The Java Set interface allows us to perform basic
mathematical set operations like union, intersection, and subset.
 Union - to get the union of two sets x and y, we can use x.addAll(y)
 Intersection - to get the intersection of two sets x and y, we can use
x.retainAll(y)
 Subset - to check if x is a subset of y, we can use y.containsAll(x)

Mrs. Divya M Patel (TMESICS) 65

The collection Interface


 Java List vs. Set:- Both the List interface and the Set interface inherits the
Collection interface. However, there exists some difference between them.
 Lists can include duplicate elements. However, sets cannot have duplicate
elements.
 Elements in lists are stored in some order. However, elements in sets are
stored in groups like sets in mathematics.

Mrs. Divya M Patel (TMESICS) 66

33
0 9 -1 2 -2 0 2 4

The collection Interface


 SortedSet Interface:- The SortedSet interface of the Java
Collections framework is used to store elements with some
order in a set.
 It extends the Set interface.
 Class that implements SortedSet:- In order to use the
functionalities of the SortedSet interface, we need to use the
TreeSet class that implements it.

Mrs. Divya M Patel (TMESICS) 67

The collection Interface


 How to use SortedSet?
 To use SortedSet, we must import the java.util.SortedSet
package first.

 We have created a sorted set called animals using the TreeSet class.
 Here we have used no arguments to create a sorted set. Hence
the set will be sorted naturally.

Mrs. Divya M Patel (TMESICS) 68

34
0 9 -1 2 -2 0 2 4

The collection Interface


 Methods of SortedSet:- The SortedSet interface includes all the methods of
the Set interface. It's because Set is a super interface of SortedSet.
 Besides methods included in the Set interface, the SortedSet interface
also includes these methods:
 comparator() - returns a comparator that can be used to order elements in the
set
 first() - returns the first element of the set
 last() - returns the last element of the set
 headSet(element) - returns all the elements of the set before the specified
element

Mrs. Divya M Patel (TMESICS) 69

The collection Interface


 tailSet(element) - returns all the elements of the set after the specified
element including the specified element
 subSet(element1, element2) - returns all the elements between the
element1 and element2 including element1

Mrs. Divya M Patel (TMESICS) 70

35
0 9 -1 2 -2 0 2 4

The collection Interface


3. Queue Interface:- The Queue interface of the Java collections framework
provides the functionality of the queue data structure.
 It extends the Collection interface.
 Classes that Implement Queue:- Since the Queue is an interface, we
cannot provide the direct implementation of it.
 In order to use the functionalities of Queue, we need to use classes that
implement it:
 ArrayDeque
 LinkedList
 PriorityQueue

Mrs. Divya M Patel (TMESICS) 71

The collection Interface

 Interfaces that extend Queue:- The Queue interface is also extended by


various subinterfaces:
 Deque
 BlockingQueue
 BlockingDeque

Mrs. Divya M Patel (TMESICS) 72

36
0 9 -1 2 -2 0 2 4

The collection Interface

 Working of Queue Data Structure:- In queues, elements are stored and


accessed in First In, First Out manner. That is, elements are added from
the behind and removed from the front.

Mrs. Divya M Patel (TMESICS) 73

The collection Interface


 How to use Queue?
 In Java, we must import java.util.Queue package in order to use Queue.

 Here, we have created objects animal1, animal2 and animal3 of classes


LinkedList, ArrayDeque and PriorityQueue respectively. These objects can
use the functionalities of the Queue interface.
Mrs. Divya M Patel (TMESICS) 74

37
0 9 -1 2 -2 0 2 4

The Collection Class (ArrayList Class)


 ArrayList Class:- In Java, we use the ArrayList class to
implement the functionality of resizable-arrays.
 It implements the List interface of the collections framework.
 Java ArrayList Vs Array:- In Java, we need to declare the
size of an array before we can use it. Once the size of an
array is declared, it's hard to change it.
 To handle this issue, we can use the ArrayList class. It
allows us to create resizable arrays.
 Unlike arrays, arraylists can automatically adjust their
capacity when we add or remove elements from them.
Hence, arraylists are also known as dynamic arrays.

Mrs. Divya M Patel (TMESICS) 75

The Collection Class (ArrayList Class)


 Creating an ArrayList:- Before using ArrayList, we need to import the
java.util.ArrayList package first. Here is how we can create arraylists in Java:

 Here, Type indicates the type of an arraylist. For example,

Mrs. Divya M Patel (TMESICS) 76

38
0 9 -1 2 -2 0 2 4

The Collection Class (ArrayList Class)


 In the above program, we have used Integer not int. It is because we cannot use
primitive types while creating an arraylist. Instead, we have to use the
corresponding wrapper classes.
 Here, Integer is the corresponding wrapper class of int.

Mrs. Divya M Patel (TMESICS) 77

The Collection Class (ArrayList Class)

Mrs. Divya M Patel (TMESICS) 78

39
0 9 -1 2 -2 0 2 4

The Collection Class (ArrayList Class)


 In the above example, we have created an ArrayList named languages.
 Here, we have used the add() method to add elements to the arraylist.
 Basic Operations on ArrayList:- The ArrayList class provides various
methods to perform different operations on arraylists. We will look at
some commonly used arraylist operations:
 Add elements
 Access elements
 Change elements
 Remove elements

Mrs. Divya M Patel (TMESICS) 79

The Collection Class (ArrayList Class)


1. Add Elements to an ArrayList:- To add a single element to the arraylist, we
use the add() method of the ArrayList class.
 Syntax of ArrayList add():-
 Here, arraylist is an object of ArrayList class.
 add() Parameters:- The ArrayList add() method can take two parameters:
 index (optional) - index at which the element is inserted
 element - element to be inserted
 If the index parameter is not passed, the element is appended to the end of the
arraylist.
 add() Return Value:- returns true if the element is successfully inserted

Mrs. Divya M Patel (TMESICS) 80

40
0 9 -1 2 -2 0 2 4

The Collection Class (ArrayList Class)

 In this example, we have created


an ArrayList named
primeNumbers.
 Here, the add() method does not
have an optional index
parameter. Hence, all the
elements are inserted at the end
of the arraylist.

Mrs. Divya M Patel (TMESICS) 81

The Collection Class (ArrayList Class)

 In this example, we have used


the add() method to insert
elements to the arraylist.
 Here, the add() method has the
optional index parameter.
Hence, C++ is inserted at index
1.

Mrs. Divya M Patel (TMESICS) 82

41
0 9 -1 2 -2 0 2 4

The Collection Class (ArrayList Class)


2. Access ArrayList Elements:- To access an element from the arraylist, we use
the get() method of the ArrayList class. For example,
 Syntax of the get() method is:-
 get() Parameter:- The get() method takes single parameter.
 index - position of the element to be accessed
 get() Return Value:-
 returns the element present in the specified position.
 raises IndexOutOfBoundsException, if index is out of the range.

Mrs. Divya M Patel (TMESICS) 83

The Collection Class (ArrayList Class)

 In this example, we have


created an arraylist named
languages. Here, the get()
method is used to access the
element present at index 1.

Mrs. Divya M Patel (TMESICS) 84

42
0 9 -1 2 -2 0 2 4

The Collection Class (ArrayList Class)


3. Change ArrayList Elements:- The Java ArrayList set() method replaces the
element present in a specified position with the specified element in an
arraylist.
 The syntax of the set() method is:-
 Here, arraylist is an object of the ArrayList class.
 set() Parameters:- The set() method takes two parameters.
 index - position of the element to be replaced
 element - new element that is to be stored at index
 set() Return Values:-
 returns the element previously present at index
 throws IndexOutOfBoundsException, if index is out of range
Mrs. Divya M Patel (TMESICS) 85

The Collection Class (ArrayList Class)

 In this example, we have created


an arraylist named languages.
 Here, we have used the set()
method to replace the element at
index 1 (English) with Java.

Mrs. Divya M Patel (TMESICS) 86

43
0 9 -1 2 -2 0 2 4

The Collection Class (ArrayList Class)


 ArrayList set() Vs. add()
 The set() method adds a new element at the specified position by replacing
the older element at that position.
 The add() method adds a new element at the specified position by shifting
the older element towards the right position.

Mrs. Divya M Patel (TMESICS) 87

The Collection Class (ArrayList Class)


4. Remove ArrayList Elements:- To remove an element from the arraylist, we
can use the remove() method of the ArrayList class.
 The remove() method removes the single element from the arraylist.
 Syntax of ArrayList remove():- The syntax of the remove() method is

 remove() Parameters:- The remove() method takes a single parameter.


 obj - element that is to be removed from the arraylist, OR
 index - position from where element is to be removed
Mrs. Divya M Patel (TMESICS) 88

44
0 9 -1 2 -2 0 2 4

The Collection Class (ArrayList Class)


 If the same element obj is present in multiple location, then the element that
appear first in the arraylist is removed.
 remove() Return Value:-
 returns true if specified element is present in the arraylist
 returns the removed element if index is passed as parameter

Mrs. Divya M Patel (TMESICS) 89

The Collection Class (ArrayList Class)

 In this example, we have


created a arraylist named
languages. The arraylist
stores the name of
programming languages.
 Here, we have used the
remove() method to remove
the element Java from the
arraylist.
25-12-2022 Ms. Uzma
Mrs. DivyaM
MShekh
Patel (TMESICS) 93
90

45
0 9 -1 2 -2 0 2 4

The Collection Class (ArrayList Class)

 In this example, we have


created an arraylist named
languages.
 Here, the remove() returns
and removes the element
present at position 2 (i.e.
Python).

Mrs. Divya M Patel (TMESICS) 91

The Collection Class (ArrayList Class)

 In this example, we have created an


arraylists named
randomNumbers. In the arraylist,
the element 13 is present in two
locations. Notice the line,

Mrs. Divya M Patel (TMESICS) 92

46
0 9 -1 2 -2 0 2 4

The Collection Class (ArrayList Class)


 Here, Integer.valueOf() - Converts the int value 13 to an Integer object. It is
because the remove() method only takes objects as its arguments.
 remove() – Removes the element 13 that appeared first in the arraylist.
 The Java ArrayList removeAll() method removes all the elements from the
arraylist that are also present in the specified collection.
 he Java ArrayList clear() method removes all the elements from an
arraylist.

Mrs. Divya M Patel (TMESICS) 93

The Collection Class (ArrayList Class)


 Both the removeAll() and clear() method are performing the same task.
 However, the clear() method is used more than removeAll().
 It is because clear() is faster and efficient compared to removeAll().

Mrs. Divya M Patel (TMESICS) 94

47
0 9 -1 2 -2 0 2 4

The Collection Class (ArrayList Class)


 Methods of ArrayList Class

Mrs. Divya M Patel (TMESICS) 95

The Collection Class (LinkedList Class)


 LinkedList Class:- The LinkedList class of the Java collections framework
provides the functionality of the linked list data structure (doubly linkedlist).
 Each element in a linked list is known as a
node. It consists of 3 fields:
 Prev - stores an address of the previous
element in the list. It is null for the
first element
 Next - stores an address of the next
element in the list. It is null for the last
element
 Data - stores the actual data
Mrs. Divya M Patel (TMESICS) 96

48
0 9 -1 2 -2 0 2 4

The Collection Class (LinkedList Class)


 Creating a Java LinkedList:-
 Here is how we can create linked lists in Java:

 Here, Type indicates the type of a linked list.

Mrs. Divya M Patel (TMESICS) 97

The Collection Class (LinkedList Class)

 In this example, we have created a


LinkedList named animals.
 Here, we have used the add()
method to add elements to the
LinkedList.

Mrs. Divya M Patel (TMESICS) 98

49
0 9 -1 2 -2 0 2 4

The Collection Class (LinkedList Class)


 Methods of Java LinkedList:- LinkedList provides various methods that
allow us to perform different operations in linked lists. We will look at four
commonly used LinkedList Operators.
 Add elements
 Access elements
 Change elements
 Remove elements
1. Add elements to a LinkedList:- We can use the add() method to add an
element (node) at the end of the LinkedList. For example,

Mrs. Divya M Patel (TMESICS) 99

The Collection Class (LinkedList Class)

 In this example, we have created a


LinkedList named animals. Here,
we have used the add() method to
add elements to animals.
 Notice the statement,

Mrs. Divya M Patel (TMESICS) 10


0

50
0 9 -1 2 -2 0 2 4

The Collection Class (LinkedList Class)


 Here, we have used the index number parameter.
 It is an optional parameter that specifies the position where the new element is
added.
2. Access LinkedList elements:- The get() method of the LinkedList class is
used to access an element from the LinkedList. For example,

Mrs. Divya M Patel (TMESICS) 10


1

The Collection Class (LinkedList Class)

 In this example, we have used


the get() method with
parameter 1.
 Here, the method returns the
element at index 1.

Mrs. Divya M Patel (TMESICS) 10


2

51
0 9 -1 2 -2 0 2 4

The Collection Class (LinkedList Class)


3. Change Elements of a LinkedList:- The set() method of LinkedList class is
used to change elements of the LinkedList. For example,

Mrs. Divya M Patel (TMESICS) 10


3

The Collection Class (LinkedList Class)

 In the above example, we have


created a LinkedList named
languages. Notice the line,

 Here, the set() method changes


the element at index 3 to
Kotlin.

Mrs. Divya M Patel (TMESICS) 10


4

52
0 9 -1 2 -2 0 2 4

The Collection Class (LinkedList Class)


4. Remove element from a LinkedList:- The remove() method of the LinkedList
class is used to remove an element from the LinkedList. For example,

Mrs. Divya M Patel (TMESICS) 10


5

The Collection Class (LinkedList Class)

 Here, the remove() method takes the


index number as the parameter.
 And, removes the element specified
by the index number.

Mrs. Divya M Patel (TMESICS) 10


6

53
0 9 -1 2 -2 0 2 4

The Collection Class (LinkedList Class)

Mrs. Divya M Patel (TMESICS) 10


7

The Collection Class (HashSet Class)


 HashSet Class:- The HashSet class of the Java Collections
framework provides the functionalities of the hash table data
structure.
 It implements the Set interface.
 Creating a HashSet:- In order to create a hash set, we must
import the java.util.HashSet package first.
 Once we import the package, here is how we can create hash sets
in Java.

Mrs. Divya M Patel (TMESICS) 10


8

54
0 9 -1 2 -2 0 2 4

The Collection Class (HashSet Class)


 Here, we have created a hash set named numbers.
 Notice, the part new HashSet<>(8, 0.75). Here, the first parameter is capacity,
and the second parameter is loadFactor.
 capacity - The capacity of this hash set is 8. Meaning, it can store 8 elements.
 loadFactor - The load factor of this hash set is 0.75. This means, whenever
our hash set is filled by 60%, the elements are moved to a new hash table of
double the size of the original hash table.
 Default capacity and load factor
 It's possible to create a hash table without defining its capacity and load
factor. For example,

Mrs. Divya M Patel (TMESICS) 10


9

The Collection Class (HashSet Class)


 By default,
 the capacity of the hash set will be 16
 the load factor will be 0.75
 Methods of HashSet:- The HashSet class provides various methods that
allow us to perform various operations on the set.
1. Insert Elements to HashSet
 add() - inserts the specified element to the set
 addAll() - inserts all the elements of the specified collection to the set

Mrs. Divya M Patel (TMESICS) 11


0

55
0 9 -1 2 -2 0 2 4

The Collection Class (HashSet Class)

Mrs. Divya M Patel (TMESICS) 11


1

The Collection Class (HashSet Class)


2. Access HashSet Elements:- To access the elements of a hash set, we can use
the iterator() method.
 In order to use this method, we must import the java.util.Iterator package.
3. Remove Elements:-
 remove() - removes the specified element from the set
 removeAll() - removes all the elements from the set

Mrs. Divya M Patel (TMESICS) 11


2

56
0 9 -1 2 -2 0 2 4

The Collection Class (HashSet Class)

Mrs. Divya M Patel (TMESICS) 11


3

The Collection Class (HashSet Class)

Mrs. Divya M Patel (TMESICS) 11


4

57
0 9 -1 2 -2 0 2 4

The Collection Class (Treeset Class)


 TreeSet Class:- The TreeSet class of the Java collections
framework provides the functionality of a tree data structure.
 It extends the NavigableSet interface.
 Creating a TreeSet:- In order to create a tree set, we must import
the java.util.TreeSet package first.
 Once we import the package, here is how we can create a TreeSet
in Java.

Mrs. Divya M Patel (TMESICS) 11


5

The Collection Class (Treeset Class)


 Here, we have created a TreeSet without any arguments. In this case, the
elements in TreeSet are sorted naturally (ascending order).
 However, we can customize the sorting of elements by using the Comparator
interface.
 Methods of TreeSet:- The TreeSet class provides various methods that allow
us to perform various operations on the set.
1. Insert Elements to TreeSet:-
 add() - inserts the specified element to the set
 addAll() - inserts all the elements of the specified collection to the set

Mrs. Divya M Patel (TMESICS) 11


6

58
0 9 -1 2 -2 0 2 4

The Collection Class (Treeset Class)

Mrs. Divya M Patel (TMESICS) 11


7

The Collection Class (Treeset Class)


2. Access TreeSet Elements:- To access the elements of a tree set, we can use
the iterator() method.
 In order to use this method, we must import java.util.Iterator package.
3. Remove Elements:-
 remove() - removes the specified element from the set
 removeAll() - removes all the elements from the set

Mrs. Divya M Patel (TMESICS) 11


8

59
0 9 -1 2 -2 0 2 4

The Collection Class (Treeset Class)

Mrs. Divya M Patel (TMESICS) 11


9

The Collection Class (Treeset Class)

Mrs. Divya M Patel (TMESICS) 12


0

60

You might also like