0% found this document useful (0 votes)
40 views31 pages

Collection

This document summarizes key Java collection interfaces and classes, including Collection, List, Set, SortedSet, LinkedList, ArrayList, Vector, Stack, and HashSet. It describes their common methods and behaviors such as storing and accessing elements. For example, List stores elements in a sequence and allows duplicate elements, while Set prohibits duplicates. Specific classes like LinkedList and ArrayList are described with examples.

Uploaded by

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

Collection

This document summarizes key Java collection interfaces and classes, including Collection, List, Set, SortedSet, LinkedList, ArrayList, Vector, Stack, and HashSet. It describes their common methods and behaviors such as storing and accessing elements. For example, List stores elements in a sequence and allows duplicate elements, while Set prohibits duplicates. Specific classes like LinkedList and ArrayList are described with examples.

Uploaded by

Bhaeath
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 31

Java Collections

 Collections are an interface in the java.util package, and as its


name suggests, it is used to define a collection of objects.

 There are many different classes which implement the collections


interface.

Collections Interfaces
Collection interface methods

 boolean add(Object obj)

Adds obj to the invoking collection. Returns true if obj was


added to the collection. Returns false if obj is already a member of
the collection, or if the collection does not allow duplicates.

 void clear( )

Removes all elements from the invoking collection.

 boolean contains(Object obj)


Returns true if obj is an element of the invoking collection.
Otherwise, returns false.

 boolean equals(Object obj)

Returns true if the invoking collection and obj are equal.


Otherwise, returns false.

 int hashCode( )

Returns the hash code for the invoking collection.

 boolean isEmpty( )

Returns true if the invoking collection is empty. Otherwise,


returns false.

 boolean remove(Object obj)

Removes one instance of obj from the invoking collection.


Returns true if the element was removed. Otherwise, returns
false.

 int size( )

Returns the number of elements held in the invoking


collection.

List Interface

The List interface extends Collection and declares the behavior of


a collection that stores a sequence of elements.

 Elements can be inserted or accessed by their position in the list,


using a zero-based index.
 A list may contain duplicate elements.

 In addition to the methods defined by Collection, List defines


some of its own, which are summarized in the following

List Interface Methods


 void add(int index, Object obj)
Inserts obj into the invoking list at the index passed in index.
Any preexisting elements at or beyond the point of insertion are
shifted up. Thus, no elements are overwritten.
 Object get(int index)
Returns the object stored at the specified index within the
invoking collection.
 int indexOf(Object obj)
Returns the index of the first instance of obj in the invoking
list. If obj is not an element of the list, -1 is returned.
 int lastIndexOf(Object obj)
Returns the index of the last instance of obj in the invoking
list. If obj is not an element of the list, -1 is returned
 Object remove(int index)
Removes the element at position index from the invoking
list and returns the deleted element. The resulting list is
compacted. That is, the indexes of subsequent elements are
decremented by one
 Object set(int index, Object obj)
Assigns obj to the location specified by index within the
invoking list.
Set Interface
 A Set is a Collection that cannot contain duplicate elements.
 The Set interface contains only methods inherited from Collection
and adds the restriction that duplicate elements are prohibited.

SortedSet Interface

 The SortedSet interface extends Set and declares the behavior of


a set sorted in ascending order.
 In addition to those methods defined by Set, the SortedSet
interface declares the methods summarized in below

SortedSet Methods
 Object first( )
Returns the first element in the invoking sorted set.
 Object last( )
Returns the last element in the invoking sorted set.
 SortedSet subSet(Object start, Object end)
Returns a SortedSet that includes those elements
between start and end-1. Elements in the returned collection are
also referenced by the invoking object.
 SortedSet headSet(Object end)
Returns a SortedSet containing those elements less than
end that are contained in the invoking sorted set.
 SortedSet tailSet(Object start)
Returns a SortedSet that contains those elements greater
than or equal to start that are contained in the sorted set.
Enumeration & Iterator

ListIterator
----------------
next() hasNext()
previous() hasPrevious()
Remove()

LinkedList
 The LinkedList class extends AbstractSequentialList and
implements the List interface.
 Apart from the methods inherited from its parent classes,
LinkedList defines following methods
LinkedList Methods
 void addFirst(Object o)
Inserts the given element at the beginning of this list.
 void addLast(Object o)
Appends the given element to the end of this list.
 Object getFirst()
Returns the first element in this list.
 Object getLast()
Returns the last element in this list
 Object removeFirst()
Removes and returns the first element from this list.
 Object removeLast()
Removes and returns the last element from this list.

LinkedList Example
import java.util.*;
class LinkedListDemo {
public static void main(String args[]) {
LinkedList ll = new LinkedList();
ll.add("F");
ll.add("B");
ll.add("D");
ll.add("E");
ll.add("C");
ll.addLast("Z");
ll.addFirst("A");
ll.add(1, "A2");
System.out.println("Original contents of ll:"+ll);
ll.remove("F");
ll.remove(2);
System.out.println("Contents of ll after deletion:"+ll);
ll.removeFirst();
ll.removeLast();
System.out.println("ll after deleting first and last:"+ll);
}}

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


Z]
Contents of ll after deletion:[A, A2, D, E, C,
Z]
ll after deleting first and last:[A2, D, E, C]

ArrayList
 The ArrayList class extends AbstractList 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.
import java.util.*;
class ArrayListDemo {
public static void main(String args[]) {
ArrayList al = new ArrayList();
System.out.println("Initial size of al:"+al.size());
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
al.add(1, "A2");
System.out.println("Size of al after additions:"+al.size());
System.out.println("Contents of al: " + al);
al.remove("F");
al.remove(2);
System.out.println("Size of al after deletions:"+al.size());
System.out.println("Contents of al: " + al);
}}

Initial size of al:0


Size of al after additions:7
Contents of al: [C, A2, A, E, B, D, F]
Size of al after deletions:5
Contents of al: [C, A2, E, B, D]
Vector
 Vector implements a dynamic array. It is similar to
ArrayList, but with two differences:
 Vector is synchronized.
 Vector contains many legacy methods that are not part of
the collections framework.
Vector Methods
 void addElement(Object obj)
Adds the specified component to the end of this vector,
increasing its size by one.
 Object firstElement()
Returns the first component (the item at index 0) of this
vector.
 Object lastElement()
Returns the last component of the vector.
 void setSize(int newSize)
Sets the size of this vector.
Ex:
import java.util.*;
class VectorDemo {
public static void main(String args[]) {
Vector v = new Vector(3, 2);
System.out.println("Initial size: " + v.size());
System.out.println("Initial capacity:"+v.capacity());
v.addElement(new Integer(1));
v.addElement(new Integer(2));
v.addElement(new Integer(3));
v.addElement(new Integer(4));
System.out.println("Capacity after four
additions:"+v.capacity());
v.addElement(new Double(5.45));
System.out.println("Current capacity:"+v.capacity());
v.addElement(new Double(6.08));
v.addElement(new Integer(7));
System.out.println("Current capacity:"+v.capacity());
System.out.println("First element:"+v.firstElement());
System.out.println("Last element:"+v.lastElement());
if(v.contains(new Integer(3)))
System.out.println("Vector contains 3.");
Enumeration vEnum = v.elements();
System.out.println("\nElements in vector:");
while(vEnum.hasMoreElements())
System.out.print(vEnum.nextElement() + " ");
System.out.println(); }}

Initial size: 0
Initial capacity:3
Capacity after four additions:5
Current capacity:5
Current capacity:7
First element:1
Last element:7
Vector contains 3.

Elements in vector:
1 2 3 4 5.45 6.08 7

Stack

 Stack is a subclass of Vector that implements a standard


last-in, first-out stack.
 Stack includes all the methods defined by Vector, and adds
several of its own.
Stack Methods
 Object peek( )
Returns the element on the top of the stack, but does not
remove it.
 Object pop( )
Returns the element on the top of the stack, removing it in
the process.
 Object push(Object element)
Pushes element onto the stack. element is also returned.
 int search(Object element)
Searches for element in the stack. If found, its offset from
the top of the stack is returned. Otherwise, -1 is returned.

Stack Example
import java.util.*;
class stackDemo {
public static void main(String args[]) {
Stack s=new Stack();
s.push(new Integer(10));
s.push(new Integer(20));
s.push(new Integer(30));
System.out.println("Elements:"+s);
System.out.println(s.peek());
System.out.println("Elements:"+s);
s.pop();
System.out.println("Elements:"+s);
}}

Elements:[10, 20, 30]


30
Elements:[10, 20, 30]
Elements:[10, 20]

HashSet
HashSet extends AbstractSet and implements the Set
interface.
HashSet Example
import java.util.*;
class HashSetDemo {
public static void main(String args[]) {
HashSet hs = new HashSet();
hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");
System.out.println(hs);
} }

[D, E, F, A, B, C]
HashSet Example
import java.util.*;
class HashSetDemo {
public static void main(String args[]) {
HashSet hs = new HashSet();
hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");
hs.add("A");//duplicate value
System.out.println(hs);
}}

[D, E, F, A, B, C]

LinkedHashSet
import java.util.*;
class HashSetDemo {
public static void main(String args[]) {
LinkedHashSet hs = new LinkedHashSet();
hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");
System.out.println(hs); } }

[B, A, D, E, C, F]

TreeSet

 TreeSet provides an implementation of the Set


interface that uses a tree for storage.
 Objects are stored in sorted, ascending order.
TreeSet Example
import java.util.*;
class HashSetDemo {
public static void main(String args[]) {
TreeSet hs = new TreeSet();
hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");
System.out.println(hs);
}}

[A, B, C, D, E, F]

TreeSet Example
import java.util.*;
class HashSetDemo {
public static void main(String args[]) {
TreeSet hs = new TreeSet(Collections.reverseOrder());
hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");
System.out.println(hs);
}}

Map Interface
 The Map interface maps unique keys to values. A key is an
object that you use to retrieve a value at a later date.
 Given a key and a value, you can store the value in a Map
object. After the value is stored, you can retrieve it by
using its key.
Map Interface Methods
 void clear( )
Removes all key/value pairs from the invoking map.
 boolean containsKey(Object k)
Returns true if the invoking map contains k as a key.
Otherwise, returns false.
 boolean containsValue(Object v)
Returns true if the map contains v as a value. Otherwise,
returns false.
 Object get(Object k)
Returns the value associated with the key k.
 boolean isEmpty( )
Returns true if the invoking map is empty. Otherwise,
returns false.
 Object put(Object k, Object v)
Puts an entry in the invoking map, overwriting any
previous value associated with the key. The key and value are
k and v, respectively. Returns null if the key did not already
exist. Otherwise, the previous value linked to the key is
returned.
 Object remove(Object k)
Removes the entry whose key equals k.
 int size( )
Returns the number of key/value pairs in the map.
SortedMap
 The SortedMap interface extends Map.
 It ensures that the entries are maintained in ascending key
order
SortedMap Methods
 Object firstKey( )
Returns the first key in the invoking map.
 SortedMap headMap(Object end)
Returns a sorted map for those map entries with keys that
are less than end.
 Object lastKey( )
Returns the last key in the invoking map.
 SortedMap subMap(Object start, Object end)
Returns a map containing those entries with keys that are
greater than or equal to start and less than end
 SortedMap tailMap(Object start)
Returns a map containing those entries with keys that are
greater than or equal to start.
HashMap Example
import java.util.*;
class hashmapdemo{
public static void main(String args[]){
HashMap h=new HashMap();
h.put(1,new String("one"));
h.put(5,new String("five"));
h.put(2,new String("two"));
System.out.println("Elements:"+h);
System.out.println(h.get(5));
h.remove(5);
System.out.println("Elements:"+h);
} }

Elements:{1=one, 2=two,
5=five}
five
Elements:{1=one, 2=two}
HashMap Example
import java.util.*;
class hashmapdemo{
public static void main(String args[]){
HashMap h=new HashMap();
h.put(1,new String("one"));
h.put(new String("hello"),new String("five"));
h.put(2,new String("two"));
h.put(new Character('a'),new String("kkkk"));
h.put(new Character('A'),new String("lll"));
h.put(new Character('b'), new String("jjjj"));
System.out.println("Elements:"+h);
} }

Elements:{hello=five, 1=one, 2=two, b=jjjj,


A=lll, a=kkkk}
TreeMap Example
import java.util.*;
class hashmapdemo{
public static void main(String args[]){
TreeMap t=new TreeMap();
t.put(1,new String("one"));
t.put(5,new String("five"));
t.put(2,new String("two"));
System.out.println("Elements:"+t);
}}

Elements:{1=one, 2=two, 5=five}

TreeMap Example
import java.util.*;
class hashmapdemo{
public static void main(String args[]){
TreeMap t=new TreeMap();
t.put(new Character('B'),new Integer(10));
t.put(new Character('C'),new Integer(20));
t.put(new Character('A'),new Integer(30));
System.out.println("Elements:"+t);
}}
Elements:{A=30, B=10, C=20}

Generics
Before Generics:
LinkedList l=new LinkedList();
l.add(new Integer(30));
Integer i=(Integer)l.get(0);

After Generics:
LinkedList<Integer> l=new LinkedList<Integer>();
l.add(new Integer(30));
Integer i=l.get(0);
LinkedList<Integer> l=new LinkedList<Integer>();
l.add(new Integer(30));
l.add(new String(“Hai”)); // Compile Time Errror
Integer i=l.get(0);

Generic class can have multiple type parameters


HashMap<String,Integer> l=new
HashMap<String,Integer>();
l.put("one", 10);
l.put(10,"ten"); // Compile Time Error

Defining Generic class


public class demo<F ,S> {
F first;
S second;
demo(F f,S s){
first=f; second=s;
}
void display(){
System.out.println("First value:"+first);
System.out.println("Second value:"+second);
}
public static void main(String [] args)
{
Integer obj=new Integer(10);
String s=new String("Hai");
demo<Integer,String> d=new
demo<Integer,String>(obj,s);
d.display();
demo<Float,Character> d1=new
demo<Float,Character>(new Float(12.34),new
Character('C'));
d1.display();
}
}

Extending the Generic Classes

class one<F,S>{
F first;
S second;
one(F f,S s){
first= f; second=s;

}
}
class two<F,S,T> extends one<F,S>{
T third;
two(F f,S s,T t){
super(f,s);
third=t;
}
void show(){
System.out.println("First value:"+first);
System.out.println("First value:"+second);
System.out.println("First value:"+third);
}
}
public class demo {

public static void main(String [] args)


{
two obj=new two(new Integer(10),new
String("hai"),new demo());
obj.show();
}
}

StringTokenizer

import java.util.StringTokenizer;
public class MyClass1{
public static void main(String args[])throws
Exception{
String s="This, is an ,example! for string@
tokenizer";
StringTokenizer st=new StringTokenizer(s,",!@");
System.out.println(st.countTokens());
while(st.hasMoreTokens()){
System.out.println(st.nextToken());
}
}
}

Output:

5
This
is an
example
for string
tokenizer
Date
import java.util.Date;
public class MyClass2 {
public static void main(String argv[]) {
Date d=new Date();
System.out.println(d);
System.out.println(d.getDate());
System.out.println(d.getDay());
System.out.println(d.getHours());
System.out.println(d.getMinutes());
System.out.println(d.getMonth());
System.out.println(d.getYear());
System.out.println(d.getSeconds());
}
}

Output:

Thu Aug 30 16:47:36 GMT+05:30 2012


30
4
16
47
7
112
36

Calendar

import java.util.Calendar;
public class MyClass3{
public static void main(String[] args) {

Calendar c=Calendar.getInstance();
System.out.println(c.get(Calendar.DATE));
System.out.println(c.get(Calendar.HOUR));
System.out.println(c.get(Calendar.SECOND));
System.out.println(c.get(Calendar.MINUTE));
System.out.println(c.get(Calendar.MONTH));
System.out.println(c.get(Calendar.YEAR));
}
}
Output:
30
4
53
48
7
2012

You might also like