0% found this document useful (0 votes)
10 views22 pages

Java 10

Chapter 10 discusses data collection in Java, focusing on arrays, multidimensional arrays, and collection classes/interfaces. It covers array creation, accessing elements, and the advantages of the Java Collection Framework, including the Map, List, and Set interfaces. Examples illustrate the use of these structures, including ArrayLists and LinkedLists, highlighting their methods and functionalities.

Uploaded by

cr7bokadai
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)
10 views22 pages

Java 10

Chapter 10 discusses data collection in Java, focusing on arrays, multidimensional arrays, and collection classes/interfaces. It covers array creation, accessing elements, and the advantages of the Java Collection Framework, including the Map, List, and Set interfaces. Examples illustrate the use of these structures, including ArrayLists and LinkedLists, highlighting their methods and functionalities.

Uploaded by

cr7bokadai
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

Chapter – 10

Holding Collection of Data


Arrays
➢ An array is a group of like – typed variable that are referred to by a common
name.
➢ Arrays in java works differently than they do in C/C++.
➢ Since arrays are object in java, we can find their length using member length.
➢ Following are some important point about java arrays.
• Java arrays variable can also be declared like other variables with[] after
the data type.
• The variables in the array are ordered and each has an index beginning
from 0.
• Java array can be also be used as a static field, a local variable or a method
parameter.
• The size of an array must be specified by an int value and not long or short.
• The direct superclass of an array type is object.
• Every array type implements the interface cloneable and
[Link].
➢ Array can contains primitives data types as well as objects of a class
depending on the definition of array.
• In case of primitives data types, the actual value are stored in contiguous
memory location.
• In case of object of a class, the actual objects are stored in heap segment.

Compiled: Nishanta Sharma Ghimire


Creating an array
➢ An array declaration has two components : the type and the name.
➢ Type declares the element type of the array. The element type determines
the data type of each element that comprises the array.
➢ Like array of int type, we can also create an array of other primitive data types
like char, float, double etc or used user defined data type (objects of a class).
For example
Datatype variable_name[];
Datatype[] variable_name;

Instantiating an array in java


➢ When an array is declared, only a reference of array is created. To actually
create or give memory to array, we create an array like this.
Variable_name = new Datatype[size];
➢ Here, data types specifies the the type of data being allocated, size specifies
the number of elements in the array and variable_name is the name of array
variable that is linked to the array.

Array literal
In a situation, where the size of the array and variables of array are already
known, array literals can be used.
Int[] intArray = new int[]{1,2,3,4,5,6,7,8,9,10}
The length of this array determines the length of the created array.
There is no need to write the new int[] part in the latest version of java.

Compiled: Nishanta Sharma Ghimire


Accessing java array elements
Each element in the array is accessed via its index. The index begins with 0 and
ends at (total array size) - 1. All the elements of array can be accessed using java
for loop.
for(int i=0; i<[Link]; i++)
[Link]("Element at index "+i+":"+arr[i]);

Example :
import [Link];
public class Array1
{
public static void main(String args[])
{
int a[] = new int[5];
int i, max, min;
Scanner sc = new Scanner([Link]);

[Link]("enter 5 numbers");
for(i=0; i<5; i++)
{
a[i] = [Link]();
}
max = a[0];
min = a[0];
for(i=1; i<5;i++)
{
if(a[i]> max)
max = a[i];
}
for(i=1;i<5;i++)
{

Compiled: Nishanta Sharma Ghimire


if(a[i]<min)
min = a[i];
}
[Link]("maximum value is: "+max);
[Link]("minimum value is: "+min);
}
}

Multidimensional Array
Multidimensional Arrays can be defined in simple words as array of arrays. Data
in multidimensional arrays are stored in tabular form.
Declaration:
type[][] variable_name = new type[rows][columns]
float[][] matrix = new float[3.5][2.55]

Example:
import [Link];

public class Array2


{
public static void main(String args[])
{
Scanner sc = new Scanner([Link]);
int rows = [Link]();
int cols = [Link]();

char alphabet[][] = new char[rows][cols];


// int[][] numbers = new int[rows][cols]

[Link]("Enter the input values");

for(int i=0; i<rows; i++)


Compiled: Nishanta Sharma Ghimire
{
for(int j=0; j<cols;j++)
{
String input = [Link]();
alphabet[i][j] = [Link](0);
}
}
[Link]("show the output values");

for(int i=0; i<rows; i++)


{
for(int j=0; j<cols; j++)
{
[Link](alphabet[i][j] +" ");
}
[Link]();
}
}
}

Collection Classes / Interfaces


➢ A collection is a group of individual objects represented as a single unit. Java
provides Collection Framework which defines several classes and interfaces
to represent a group of objects as a single unit.
➢ The collection interface ([Link]) and map interface
([Link]) are the two main “root” interfaces of java collection classes.
Advantages of Collection Framework:
➢ Before collection framework ( or before JDK 1.2 ) was introduced, the
standard methods for grouping java objects (or collections) were Arrays or
Vectors or Hashtables. All of these collections had no common interface.
➢ Accessing elements of these Data Structures was a hassle as each had a
different method ( and syntax ) for accessing its members.
1. Consistent API: The API has a basic set of interfaces like collection, set, List
or Map. All classes (ArrayList, LinkedList, Vector etc) that implements
these interfaces have some common set of methods.

Compiled: Nishanta Sharma Ghimire


2. Reduces programming effort: A programmer doesn’t have to worry about
the design of collection and he can focus on its best use in his program.
3. Increases program speed and quality: Increases performance by providing
high performance implementations of useful data structures and
algorithms.
Collection Interfaces
1. Map Interface
The [Link] interface represents a mapping between a key and a value.
Few characteristics of the Map Interface are:
➢ A Map cannot contain duplicate keys and each key can map to at most one
value. Some implementations allow null key and null value like the HashMap
and LinkedHashMap but some do not like the TreeMap.
➢ The order of a map depends on specific implementations e.g TreeMap and
LinkedHashMap have predictable order, while HashMap does not.
➢ There are two interfaces for implementing Map in java: Map and SortedMap
and three classes: HashMap, TreeMap and LinkedHashMap.
Methods in Map Interface:
1. put(key, value): This method is used to insert an entry in this map.
2. putAll(Map map): This method is used to insert the specified map in this map.
3. remove(key): This method is used to delete an entry for the specified key.
4. get(key): This method is used to return the value for the specified key.
5. containskey(key): This method is used to search the specified key from this
map.
6. clear(): This method clear all the elements.
7. size(): This method returns the number of components.
8. Keyset(): Gives all the keys.

Example:
import [Link];
import [Link];

class MapInterface
{
public static void main(String args[])
{
Map<String , Integer> students = new HashMap<>();
[Link]("Sudip", 56);
[Link]("Chesta", 23);

Compiled: Nishanta Sharma Ghimire


[Link]("Keshab", 67);
[Link]("nainesh", 98);
[Link]("nainesh", 72);

[Link](students);
//[Link]([Link]("Sudip"));

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

for(String key : [Link]())


{
[Link](key + ": " +[Link](key));
}
}
}
Output:
{Keshab=67, Sudip=56, nainesh=72, Chesta=23}
[Keshab, Sudip, nainesh, Chesta]
[67, 56, 72, 23]
Keshab: 67
Sudip: 56
nainesh: 72
Chesta: 23

Compiled: Nishanta Sharma Ghimire


2. List interface:
The [Link] is a child interface of collection. It is an ordered collection of
objects in which duplicate values can be stored. Since list preserves the insertion
order, it allows positional access and insertion of elements. List interface is
implemented by ArrayList, LinkedList, Vector and Stack Classes.
List is an interface and the instances of List can be created in the following ways:
List a = new ArrayList();
List b = new LinkedList();
List c = new Vector();
List d = new Stack();

Methods in List Interface:


1. add(element): This method is used to add elements in list.
2. get(index): This method is used to retrieve elements on the basis of index
number.
3. isEmpty(): This method tests if this list has no components.
4. remove(index): This method removes a single elements on the basis of index
number.
5. clear(): This method clear all the elements from list.
6. size(): This method returns the number of components in this list.
7. removeAllElements(): This method removes all components from this list and
sets its size to zero.
8. indexOf(element): This method returns first occurrence of given element or
–1 if element is not present in list.
9. lastIndexOf(element): This method returns the last occurrence of given
element or –1 if element is not present in list.
Example:
import [Link];
import [Link];

class ListInterface
{
public static void main (String args[])
{
List li = new ArrayList<>();
//adding items
[Link](10);

Compiled: Nishanta Sharma Ghimire


[Link](20);
[Link](30);
[Link](40);
[Link](5);

// retrieving items
[Link](li);
[Link]("item at index 1 is: "+[Link](1));

//removing item
[Link](2);
[Link]("After removing item: "+ li);

//getting size
[Link]("Size of list: "+ [Link]());

// removing all items


[Link]();
[Link]("After removing all items: "+li);
}
}
Output:
[10, 20, 30, 40, 5]
item at index 1 is: 20
After removing item: [10, 20, 40, 5]
Size of list: 4
After removing all items: []

Compiled: Nishanta Sharma Ghimire


3. Set Interface:
➢ Set is an interface which extends collection. It is an unordered collection of
objects in which duplicate values cannot be stored.
➢ Basically, Set is implemented by HashSet, LinkedHashSet or TreeSet (Sorted
representation).
➢ Set has various methods to add, remove clear, size etc to enhance the usage
of this interface.
Methods in Set interface:
1. Add(element): This method is used to add element in set.
2. Get(index): This method is used to retrieve elements on the basis of index
number.
3. IsEmpty(): This method tests if this set has no components.
4. Remove(index): This method removes a single element on the basis of index
number.
5. Clear(): This method clear all the elements from set.
6. Size(): This method returns the number of components in this set.
7. RemoveAllElements(): This method removes all components from this set
and sets its size to zero.
8. IndexOf(element): This method returns first occurrence of given element or
–1 if element is not present in set.
9. LastIndexOf(element): This method returns the last occurrence of given
element or –1 if element is not present in set.
Example:
import [Link];
import [Link];
import [Link];

class SetInterface
{
public static void main(String args[])
{
//Set<String> s1 = new HashSet<String>();
Set<String> s1 = new TreeSet<String>();
[Link]("Keshab");
[Link]("sudip");
[Link]("preshu");
[Link]("sushan");
[Link]("sudip");

Compiled: Nishanta Sharma Ghimire


[Link](s1);
}
}
Output
Set in Hashset:
[Keshab, sudip, sushan, preshu]
Set in Treeset:
[Keshab, preshu, sudip, sushan]

Collection classes:
[Link] List:
➢ The ArrayList class extends Abstract List and implements the List interface.
➢ ArrayList supports dynamic arrays that can grow as needed.
➢ Standard java arrays are of a fixed length. After arrays are created, they
cannot grow or shrink, which means that you must know in advance how
many elements an array will hold.
➢ Array lists are created with an initial size. When this size is exceeded, the
collection is automatically enlarged. When objects are removed, the array
may be shrunk.
Methods of ArrayList
add(), get(), remove(), size(), clear(), isEmpty(), indexOf(), Contains(), get()
Example:
import [Link];

class Arraylist1
{
public static void main(String args[])
{
ArrayList<String> al = new ArrayList();
[Link]("Initial size of array list: "+[Link]());

// add elements to the array list


[Link]("N");

Compiled: Nishanta Sharma Ghimire


[Link]("I");
[Link]("S");
[Link]("H");
[Link]("A");
[Link]("N");
[Link]("T");
[Link]("A");

[Link]("Size of array list after addition:


"+[Link]());

// display the array list


[Link]("content of array list:" +al);

// Remove elements from the array list


[Link]("N");
[Link](1);
[Link]("size of array list after deletion:
"+[Link]());
[Link]("content of arraylist: "+al);
}
}

Output:
Initial size of array list: 0
Size of array list after addition: 8
content of array list:[N, I, S, H, A, N, T, A]
size of array list after deletion: 6
content of arraylist: [I, H, A, N, T, A]

Compiled: Nishanta Sharma Ghimire


2. Linked List:
➢ Like arrays, linked list is a linear data structure. Unlike arrays, linked list
elements are not stored at the contiguous location, the elements are linked
using pointer.
➢ Methods are same as arraylist.
Example:
import [Link];

class Linkedlist1
{
public static void main(String args[])
{
LinkedList<String> li = new LinkedList<String>();
[Link]("Initial size of list: "+[Link]());

// add elements to the array list


[Link]("N");
[Link]("I");
[Link]("S");
[Link]("H");
[Link]("A");
[Link]("N");
[Link]("T");
[Link]("A");
[Link](1, "A2");

[Link]("Size of array list after addition:


"+[Link]());

// display the array list


[Link]("content of array list:" +li);

// Remove elements from the array list

Compiled: Nishanta Sharma Ghimire


[Link]("A");
[Link](1);
[Link]("size of array list after deletion:
"+[Link]());
[Link]("content of list: "+li);

}
Output:
Initial size of list: 0
Size of array list after addition: 9
content of array list:[N, A2, I, S, H, A, N, T, A]
size of array list after deletion: 7
content of list: [N, I, S, H, N, T, A]

Hash Map
➢ HashMap is a part of java collection since java 1.2.
➢ It provides the basic implementation of Map interface of [Link] stores the
data in(Key, Value) pairs.
➢ To access a value one must know its key. HashMap is known as HashMap
because it uses a techniques called hashing.
➢ Hashing is a techniques of converting a large string to small string that
represents the same string.
➢ A shorter value helps in indexing and faster searches.

Methods is same as Hash set.


Example:
import [Link];

public class HashMap1


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

Compiled: Nishanta Sharma Ghimire


HashMap<Integer, String> map = new HashMap<>();
[Link](10, "Nishanta");
[Link](12, "keshab");
[Link](16, "sushan");

[Link](map);
[Link]("size of map is: "+[Link]());

if ([Link](16))
{
String st = [Link](16);
[Link]("value for key 16 is: "+st);
}

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

[Link]();
[Link]("after clearing map: "+map);
}
}
Output:
{16=sushan, 10=Nishanta, 12=keshab}
size of map is: 3
value for key 16 is: sushan
[16, 10, 12]
[sushan, Nishanta, keshab]
after clearing map: {}

Compiled: Nishanta Sharma Ghimire


Hash Set
➢ The HashSet class implements the set interface, backed by a hash table which
is actually a HashMap instance. Few important features of HashSet are
• Implements Set interface.
• Underlying data structures for HashSet is hashtable.
• As it implements the set interface, duplicate values are not allowed.
• Objects that you insert in HashSet are not guaranteed to be inserted in
same order.
• Objects are inserted based on their hash key.
• NULL elements are allowed in HashSet.
Methods are similar to map set interface.
Example:
import [Link];

public class Hash_Set


{
public static void main(String args[])
{
HashSet<String> hs = new HashSet<String>();

// Adding elements into Hashset


[Link]("India");
[Link]("Nepal");
[Link]("Pakistan");
[Link]("Bangladesh");
[Link]("Afganistan");
[Link]("India");

//Displaying the Hashset


[Link](hs);
[Link]("List contains India or not:
"+[Link]("India"));

// Removing items from HashSet using remove()

Compiled: Nishanta Sharma Ghimire


[Link]("Pakistan");
[Link]("List after removing pakistan: "+hs);
}
}
Output:
[Bangladesh, Pakistan, Afganistan, Nepal, India]
List contains India or not: true
List after removing pakistan: [Bangladesh, Afganistan, Nepal, India]

Tree Set
TreeSet is one of the most important implementations of the SortedSet
interface in java that uses a Tree for storage. The ordering of the elements is
maintained by a set using their natural ordering whether or not an explicit
comparator is provided. This must be consistent with equals if it is to correctly
implement the Set interface.
Few important features of TreeSet are as follows:
➢ TreeSet implements the SortedSet interface so duplicate values are not
allowed.
➢ Objects in a TreeSet are stored in a sorted and ascending order.
➢ TreeSet does not preserve the insertion order of elements but elements are
sorted by keys.
➢ TreeSet does not allow to insert Heterogeneous objects. It will throw
classCastException at Runtime if trying to add heterogeneous objects.
➢ TreeSet serves as an excellent choice for storing large amounts of sorted
information which are supported to be accessed quickly because of its faster
access and retrieval time.
Methods are same as set interface.

Example:
import [Link];

public class Treeset


{
public static void main(String args[])
{
TreeSet<String> Ts = new TreeSet<String>();

Compiled: Nishanta Sharma Ghimire


// Adding elements into Treeset
[Link]("India");
[Link]("Nepal");
[Link]("Pakistan");
[Link]("Bangladesh");
[Link]("Afganistan");
[Link]("India");

//Displaying the Treeset


[Link](Ts);
[Link]("List contains India or not:
"+[Link]("India"));

// Removing items from TreeSet using remove()


[Link]("Pakistan");
[Link]("List after removing pakistan:
"+Ts);
}
}
Output:
[Afganistan, Bangladesh, India, Nepal, Pakistan]
List contains India or not: true
List after removing pakistan: [Afganistan, Bangladesh, India, Nepal]

Iterator
In Java, an iterator is an interface provided by the [Link] package that allows you to
traverse elements of a collection (such as ArrayList, LinkedList, HashSet, etc.) in a
sequential manner. It provides a standardized way to access elements of a collection
without exposing the underlying implementation details.
The Iterator interface defines three main methods:
➢ boolean hasNext(): Returns true if there are more elements in the collection to be
iterated, and false otherwise.

Compiled: Nishanta Sharma Ghimire


➢ E next(): Returns the next element in the collection and advances the iterator to the
next position. The type E represents the type of elements in the collection.
➢ void remove(): Removes the last element returned by the iterator from the
underlying collection. This method is optional and not all collections support it.

Example:
import [Link];
import [Link];

class iterator1
{
public static void main(String args[])
{
ArrayList<String> al = new ArrayList<String>();

// add elements to the array list


[Link]("N");
[Link]("I");
[Link]("S");
[Link]("H");
[Link]("A");
[Link]("N");
[Link]("T");
[Link]("A");

Iterator<String> values = [Link]();

while([Link]())
[Link]([Link]());
}
}

Compiled: Nishanta Sharma Ghimire


Comparator
A comparator interface is used to order the objects of user-defined classes. A
comparator object is capable of comparing two objects of the same class.
Following function compare obj1 with obj2.
Syntax
public int compare(Object obj1, Object obj2)
Suppose we have an Array/ArrayList of our own class type, containing fields like
roll no, name, address, DOB, etc, and we need to sort the array based on Roll no
or name?
Method 1: One obvious approach is to write our own sort() function using one
of the standard algorithms. This solution requires rewriting the whole sorting
code for different criteria like Roll No. and Name.
Method 2: Using comparator interface- Comparator interface is used to order
the objects of a user-defined class. This interface is present in [Link] package
and contains 2 methods compare(Object obj1, Object obj2) and equals(Object
element). Using a comparator, we can sort the elements based on data
members. For instance, it may be on roll no, name, age, or anything else.
Example:
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class comparator


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

Comparator<Integer> com = new Comparator<Integer>()


{
public int compare(Integer i, Integer j)
{
if(i%10 > j%10)

Compiled: Nishanta Sharma Ghimire


return 1;
else
return -1;
}

};

List<Integer> li = new ArrayList<Integer>();


//adding items
[Link](43);
[Link](10);
[Link](32);
[Link](27);
[Link](5);
[Link](41);

[Link](li,com);
[Link](li);
}
}
Output:
[10, 41, 32, 43, 5, 27]

Compiled: Nishanta Sharma Ghimire


Compiled: Nishanta Sharma Ghimire

You might also like