Java
Java
Collection is an object which stores other objects inside it. Unlike an array size
of a collection can be changed dyanamically. So elements can be added or removed
from a collection at runtime.
java.util.Collection interface
In a collection, we cannot store any primitive values but we can only store objects
of same or different class type as elements in a collection.
1. java.util.List interface:
List interface is used for generating lists in java. A list is the data structure
or collection in which insertion order of elements is preserved i.e. order in which
we enter elements inside a list will be same as order in which they are stored in
list.
e.g. If we enter 3 elements in a list say 1st element is a String class obejct with
value "abc def", 2nd element is Integer wrapper class object, 3rd element is a
Student class object s1, then the elements are stored in same order in list.
In a list we can also store duplicate elements i.e. elements with same value.
e.g. If we enter 1st 2 elements in a list as "abc def","kaveesh nadkarni". If we
try to enter a 3rd element into the list with value "abc def" which is already the
value of existing elements in the list, then we can easily insert the new element
with value "abc def". So now there will be 2 elements in same list object with same
value "abc def".
java.util.List interface
Stack
java.util.ArrayList class,LinkedList class and Vector class are the 3 direct
subclasses of java.util.List interface.
java.util.Collection interface
In a collection, we cannot store any primitive values but we can only store objects
of same or different class type as elements in a collection.
-------------------------------------------------------------------------------
1. java.util.List interface:
List interface is used for generating lists in java. A list is the data structure
or collection in which insertion order of elements is preserved i.e. order in which
we enter elements inside a list will be same as order in which they are stored in
list.
e.g. If we enter 3 elements in a list say 1st element is a String class object with
value "abc def", 2nd element is Integer wrapper class object, 3rd element is a
Student class object s1, then the elements are stored in same order in list.
In a list we can also store duplicate elements i.e. elements with same value.
e.g. If we enter 1st 2 elements in a list as "abc def","kaveesh nadkarni". If we
try to enter a 3rd element into the list with value "abc def" which is already the
value of existing elements in the list, then we can easily insert the new element
with value "abc def". So now there will be 2 elements in same list object with same
value "abc def".
java.util.List interface
Stack
java.util.ArrayList class,LinkedList class and Vector class are the 3 direct
subclasses of java.util.List interface.
import java.util.*;
import java.io.*;
class Main
{
public void opns()throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
Scanner sc=new Scanner(System.in);
System.out.println("\n Enter how many elements to stored in
arraylist:");
int n=sc.nextInt();
ArrayList<String> l1=new ArrayList<String>();
/*
In above statement while declaring reference variable l1 of ArrayList class, we
have mentioned generic type String for l1. So this means that we can store only
objects of STring class type into l1 now. So l1 is a homogenous collection. But if
we wanted to store objects of different class types into l1, then we can write:
*/
for(int i=1;i<=n;i++)
{
String str=br.readLine();
l1.add(str);
}
/*
Here the above loop runs n no. of times, so each time the loop runs, we are
accepting a string value from user and storing it into str variable and then adding
str variable value to end of list l1. So after the loop completely runs, n no. of
string values would be stored into l1.
*/
System.out.println("\n The "+n+" number of string values stored into l1
are:");
for(String s1:l1)
{
System.out.println(s1);
}
for(int i=0;i<=l1.size()-1;i++)
{
System.out.println(l1.get(i));
//l1.get(i) returns the value of element at index i in l1. Just like in array in
a //list also index counting begins from 0
Iterator<String> i1=l1.iterator();
/*
The Iterator name mentioned on LHS of the above statement is a predefined interface
of java.util package. It is also called as cursor. Cursors are those interfaces in
java.util packlage which are used for accessing elements in a collection.
iterator() mentioned on RHS of the above statement is a predefined non static
member method of ArrayList class and it will return an implicit object of Iterator
interface which we have assigned to reference variable i1 of Iterator interface.
Using i1 object of Iterator interface we can access elements of arraylist l1.
We have also mentioned <String> as the generic type of Iterator interface ref. var.
i1 because we are using i1 to access elements of collection list l1 whose generic
type is String.
*/
while(i1.hasNext())
{
System.out.println(i1.next());
}
/*
hasNext() and next() are prdefined non static member methods of Iterator interface.
*/
while(li1.hasNext())
{
System.out.println(li1.next());
while(li1.hasPrevious())
{
System.out.println(li1.previous());
}
/*
using above loop we have accessed elements in list l1 using list iterator object
li1 in reverse direction. But for accessing elements in list in revrese direction
we first need to go to end of list l1 using list iterator li1 in forward direction
*/
while(i1.hasNext())
{
System.out.println(i1.next());
while(i1.hasNext())
{
System.out.println(i1.next());
l1.addAll(l3);
while(i1.hasNext())
{
System.out.println(i1.next());
Object arr1[]=l1.toArray();
//above statement returns elements of list l1 as a 1d array where reference type of
1d array returned by l1.toArray() is of //java.lang.Object class,where
java.lang.Object class is the superclass of every class in java
System.out.println(str11);
}
List l4=Arrays.asList(arr1);
//above statement returns elements of arr1 array as a general list and so we must
declare l4 as a reference variable of the //java.util.List interface, asList() is a
predefined static member method of java.util.Arrays class
Collections.sort(l1);
//above statement automatically sorts the elements present in l1 in ascending order
where Collections is a predefined clas sin //java.util package and sort() is its
predefined static member method
while(i1.hasNext())
{
System.out.println(i1.next());
Arrays.sort(arr1);
//sort() is a predefined static member method in java.util.Arrays class and it will
automatically sort the elements in arr1 in //alphabetical order
}
}
/*
Vector class:
Vector is a predefined class in java.util package.
int arr1[];
arr1=new int[100];
arr1=new int[500];
Vector object is synchronized or thread safe. This means that multiple threads
cannot access the same Vector object at same time. This also means that pgms
involving Vector class are slower than pgms involving ArrayList and LinkedList
class because AL and LL are non synchronized.
The extra member functions of Vector which are not in other classes which implement
list, mostly contain word element. e.g. addElement()
*/
import java.io.*;
import java.util.*;
class MyClass1
{
public void vector_opns()throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
Vector<String> v1=new Vector<String>();
/*
When we declare a reference variable of collection class type, we can also
optionally mention the class type of elements or individual objects which can be
stored as a part of collection. Here we are telling java compiler that we want to
store objects of String type in Vector object v1.
If we wanted we could have also declared and created Vector object v1 without
mentioning any type in <>.
Vector v1=new Vector();
Now v1 can store objects of any class type in it.
The class type of objects which can be stored into a collection is generic type of
the collection.
Cursors are those objects in collection, which are used to access elements of
collection. There are 3 types of cursors Iterator,ListIterator and Enumeration.
*/
int n;
System.out.println("\n Enter how many elements of string type do you
want to store in vector:");
n=Integer.parseInt(br.readLine());
for(int i=1;i<=n;i++)
{
System.out.println("\n Enter string value no."+i);
String str=br.readLine();
v1.add(str);
/*
* v1.add(str) adds a new element of string value stored in
str to end of v1 vector.
* v1.addElement(str) is also same as v1.add(str)
*/
}
Iterator<String> i1=v1.iterator();
/*
* Iterator is a predefined interface in java.util package. Here in
above statement v1.iterator() returns an implicit
* object of Iterator interface which we have assigned to i1 variable.
Now using i1 object we can access elements in vector v1.
*
*/
Enumeration<String> e1=v1.elements();
//very similar to v1.ietartor(), but v1.elements() returns implicit
object of java.util.Enumeration interface
//which we can use to access elements of vector
System.out.println("\n The elements of vector using enumeration are:");
while(e1.hasMoreElements())
{
System.out.println(e1.nextElement());
}
String str3;
System.out.println("\n Which element do you want to search. Please
enter string value");
str3=br.readLine();
System.out.println("\n The fact that "+str3+" is present in vector is
"+v1.contains(str3));
*/
System.out.println("\n Enter value of element whose idnex of last
occurance you want:");
str4=br.readLine();
System.out.println("\n Index of last occurance of "+str4+" is
"+v1.lastIndexOf(str4));
/*
"abc def","mno pqr","xyz"
v1.insertElementAt("kaveesh",1);
"abc def","kaveesh","mno pqr","xyz"
*/
System.out.println("\n The elements in vector v1 adfter inserting
element using for each loop are:");
for(String str1:v1)
{
System.out.println(str1);
}
ListIterator<String> l1=v1.listIterator();
//ListIterator helps us to move in forward and backward direction in
vector
System.out.println("\n The elements of vector in forward direction
using list iterator are:");
while(l1.hasNext())
{
System.out.println(l1.next());
}
System.out.println("\n The elements of vector in backward direction
using list iterator are:");
while(l1.hasPrevious())
{
System.out.println(l1.previous());
}
v1.clear();//removes all elements from vector
System.out.println("\n The fact that vector is empty is
"+v1.isEmpty());
}
public static void main(String[] args) throws IOException
{
MyClass1 mc1=new MyClass1();
mc1.vector_opns();
}
import java.util.*;
import java.io.*;
class MyClass2
{
public void linkedList_opns()throws IOException
{
Scanner sc=new Scanner(System.in);
LinkedList<String> list1=new LinkedList<String>();
/*
When we declare a reference variable of collection class type, we can also
optionally mention the class type of elements or individual objects which can be
stored as a part of collection. Here we are telling java compiler that we want to
store objects of String type in LinkedList object list1.
If we wanted we could have also declared and created LinkedList object list1
without mentioning any type in <>.
LinkedList list1=new LinkedList();
Now list1 can store objects of any class type in it.
The class type of objects which can be stored into a collection is generic type of
the collection.
*/
int n;
System.out.println("\n Enter how many elements of string type do you
want to store in LinkedList:");
n=sc.nextInt();
for(int i=1;i<=n;i++)
{
System.out.println("\n Enter string value no."+i);
String str=sc.next();
list1.add(str);
/*
* list1.add(str) adds a new element of string value stored
in str to end of list1 LinkedList.
*
*/
}
System.out.println("\n The elements in LinkedList using for each loop
are:");
for(String str1:list1)
{
System.out.println(str1);
}
System.out.println("\n The elements in LinkedList using normal for loop
are:");
for(int i=0;i<=list1.size()-1;i++)
{
System.out.println(list1.get(i));
//list1.get(i) returns elemenmt at index i in LinkedList list1
}
Iterator<String> i1=list1.iterator();
/*
* Iterator is a predefined interface in java.util package. Here in
above statement list1.iterator() returns an implicit
* object of Iterator interface which we have assigned to i1 variable.
Now using i1 object we can access elements in LinkedList list1.
*
*/
System.out.println("\n The elements of LinkedList using iterator
are:");
while(i1.hasNext())
{
//i1.hasNext() checks if there are any more elements to be
accessed of LinkedList object list1 using i1 object
//if yes then true
System.out.println(i1.next());
//i1.next() returns next element in LinkedList
}
int index;
System.out.println("\n Enter at which index do you want to remove
element:");
index=sc.nextInt();
System.out.println("\n The element at index "+index+" having value
"+list1.remove(index)+" has been removed ");
System.out.println("\n The elements in LinkedList list1 adfter removing
using for each loop are:");
for(String str1:list1)
{
System.out.println(str1);
}
String str2;
System.out.println("\n Enter value of element to be removed:");
str2=sc.next();
System.out.println("\n The fact that element with value str2 has been
removed is "+list1.remove(str2));
System.out.println("\n The elements in LinkedList list1 adfter
removing using for each loop are:");
for(String str1:list1)
{
System.out.println(str1);
}
String str3;
System.out.println("\n Which element do you want to search. Please
enter string value");
str3=sc.next();
System.out.println("\n The fact that "+str3+" is present in LinkedList
is "+list1.contains(str3));
String str4;
System.out.println("\n Enter value of element whose index of 1st
occurance you want:");
str4=sc.next();
System.out.println("\n Index of 1st occurance of "+str4+" is
"+list1.indexOf(str4));
/*
List interface
ArrayList LinkedList Vector
Stack
In a stack, elements are added one above other. The concept of stack is based on
Last in first out. So last element which is added to stack is 1st element removed
from stack.
*/
//java pgm for stack
import java.util.*;
class Collection2
{
Stack<String>s1=new Stack<String>();
//s1 is the type safe collection where only String class objects can be added
to it
void opns()
{
s1.push("kaveesh nadkarni");
s1.push("kaveesh nadkarni1");
s1.push("kaveesh nadkarni2");
s1.push("kaveesh nadkarni3");
s1.push("kaveesh nadkarni4");
int flag=s1.search("kaveesh nadkarni2");
/*
* searches for the element in the stack and returns the location of
* the element from the top of the stack if it is present and if
element
* is not present then we get -1. It returns 3
*/
if(flag>=0)
{
System.out.println("\n the element kaveesh nadkarni 2 is present
in the stack and its location from the top of the stack is "+flag);
}
else
System.out.println("\n the element kaveesh nadkarni2 is not
present in the stack");
String name=s1.peek();
/*
* returns the top most element from the stack without popping it
*/
System.out.println("\n the elements at the top of the stack without
popping is "+name);
while((s1.size())!=0)//returns the total number of elements in the
stack
{
System.out.println("\n the popped element is "+s1.pop());
}
System.out.println("\n the fact that the stack is empty is
"+s1.isEmpty());
//s1.isEmpty() will only check if stack is empty or not but will not actually empty
it
}
public static void main(String args[])
{
Collection2 c2=new Collection2();
c2.opns();
}
}
//LIFO
//Last in first out
/*
9
8
11
2
3
*/
//hashset in java
/*
* Set is a predfined interface in java.util package. It is the sub interface
* of the Collection interface.
*
Collection interface
Set interface
TreeSet class
*
*
* HashSet:
* Here it is a predefined class in java.util package which implements the Set
interface.
*
* HashSet is based on the underlying data structure called as hash table.
*
* In hashset ,if we try to store duplicate elements, then we wont get a compiler
* error but we get false value means the element has not been added to the
hashset.
*
* in hashset the insertion order is not preserved. So in hashset we cannot access
elements using index.
*
* because in the hashset the elements are stored as per their hashcode.
*
* In hashset we can enter null value only once because duplicate elements
* are not allowed in the hashset.
In hashtable, the elements are accessed using hash function which when
applied to an element value returns index of element in hashset.
*
*
*
* LinkedHashSet is the sub class of HashSet.
*
* In LinkedHashSet the underlying data structure is hash table and doubly linked
list
*
* in linked hashset the null element can be added only once in the linked hash
set.
*
* because duplicate elements are not allowed.
*
* in linked hashset the insertion order is preserved means the order in which
* the elements are stored is same as the order in which they were inserted.
*
In a set or in any of its subclasses we cannot access elements using index.
*/
//PGM of hashset
/*
* IN Set interface, we dont have our own methods. But all the methods of the Set
* interface are those defined in the Collection interface which is the
* super interface of the Set interface.
*/
import java.util.*;
class Set1
{
HashSet<String>hs=new HashSet<String>();
/*
* when we create the object of the HashSet, we can supply 2 arguments
* to its constructor.
*
* 1st is the initial capacity of the hashset and 2nd is the load factor of
the hashset.
*
* the load factor is always a fractional number of float data type and it
should
* be generally less than 1.
*
* by default the initial capacity is 16 and load factor is 0.75
*
* so multiply 16 by 0.75 we get 12. so this means that after the size of the
* hashset reaches 12, then the capacity of the hashset will automatically be
increased
* but by how much amount it will be increased in out ofour hands, it is
dependent
* on the JVM
*/
void opns()
{
/*
* in hashset the element cannot be aaccessed by index
*/
hs.add("kaveesh nadkarni");
hs.add("vivek anand nadkarni");
hs.add("rajaram savkoor");
hs.add("abc def");
/*