Java Collection Framework
Java Collection Framework
o is optional.
2. Algorithm
3 public boolean remove(Object element) is used to delete an element from this collection.
4 public boolean removeAll(Collection c) is used to delete all the elements of specified collection from the invoking
collection.
5 public boolean retainAll(Collection c) is used to delete all the elements of invoking collection except the specified
collection.
6 public int size() return the total number of elements in the collection.
7 public void clear() removes the total no of element from the collection.
9 public boolean containsAll(Collection c) is used to search the specified collection in this collection.
Iterator interface
Iterator interface provides the facility of iterating the elements in forward direction only.
Methods of Iterator interface
There are only three methods in the Iterator interface. They are:
2. public object next() it returns the element and moves the cursor pointer to the next element.
3. public void remove() it removes the last elements returned by the iterator. It is rarely used.
o Java ArrayList allows random access because array works at the index basis.
o In Java ArrayList class, manipulation is slow because a lot of shifting needs to be occurred if any element is removed from the array
list.
1. public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, Serializable
ArrayList(Collection c) It is used to build an array list that is initialized with the elements of the collection c.
ArrayList(int capacity) It is used to build an array list that has the specified initial capacity.
void add(int index, Object It is used to insert the specified element at the specified position index in a list.
element)
boolean addAll(Collection c) It is used to append all of the elements in the specified collection to the end of this list, in the
order that they are returned by the specified collection's iterator.
void clear() It is used to remove all of the elements from this list.
int lastIndexOf(Object o) It is used to return the index in this list of the last occurrence of the specified element, or -1 if the
list does not contain this element.
Object[] toArray() It is used to return an array containing all of the elements in this list in the correct order.
Object[] toArray(Object[] a) It is used to return an array containing all of the elements in this list in the correct order.
boolean add(Object o) It is used to append the specified element to the end of a list.
boolean addAll(int index, It is used to insert all of the elements in the specified collection into this list, starting at the specified
Collection c) position.
int indexOf(Object o) It is used to return the index in this list of the first occurrence of the specified element, or -1 if the
List does not contain this element.
void trimToSize() It is used to trim the capacity of this ArrayList instance to be the list's current size.
Java new generic collection allows you to have only one type of object in collection. Now it is type safe so typecasting is not required at run
time.
In generic collection, we specify the type in angular braces. Now ArrayList is forced to have only specified type of objects in it. If you try to
add another type of object, it gives compile time error.
For more information of java generics, click here Java Generics Tutorial.
1. By Iterator interface.
2. By for-each loop.
In the above example, we have seen traversing ArrayList by Iterator. Let's see the example to traverse ArrayList elements using for-each
loop.
1. class Student{
2. int rollno;
3. String name;
4. int age;
5. Student(int rollno,String name,int age){
6. this.rollno=rollno;
7. this.name=name;
8. this.age=age;
9. }
10. }
1. import java.util.*;
2. public class TestCollection3{
3. public static void main(String args[]){
4. //Creating user-defined class objects
5. Student s1=new Student(101,"Sonoo",23);
6. Student s2=new Student(102,"Ravi",21);
7. Student s2=new Student(103,"Hanumat",25);
8. //creating arraylist
9. ArrayList<Student> al=new ArrayList<Student>();
10. al.add(s1);//adding Student class object
11. al.add(s2);
12. al.add(s3);
13. //Getting Iterator
14. Iterator itr=al.iterator();
15. //traversing elements of ArrayList object
16. while(itr.hasNext()){
17. Student st=(Student)itr.next();
18. System.out.println(st.rollno+" "+st.name+" "+st.age);
19. }
20. }
21. }
Test it Now
101 Sonoo 23
102 Ravi 21
103 Hanumat 25
1. import java.util.*;
2. class Book {
3. int id;
4. String name,author,publisher;
5. int quantity;
6. public Book(int id, String name, String author, String publisher, int quantity) {
7. this.id = id;
8. this.name = name;
9. this.author = author;
10. this.publisher = publisher;
11. this.quantity = quantity;
12. }
13. }
14. public class ArrayListExample {
15. public static void main(String[] args) {
16. //Creating list of Books
17. List<Book> list=new ArrayList<Book>();
18. //Creating Books
19. Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
20. Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill",4);
21. Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
22. //Adding Books to list
23. list.add(b1);
24. list.add(b2);
25. list.add(b3);
26. //Traversing list
27. for(Book b:list){
28. System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
29. }
30. }
31. }
Test it Now
Output:
Java HashSet class is used to create a collection that uses a hash table for storage. It inherits the AbstractSet class and implements Set
interface.
HashSet(Collection It is used to initialize the hash set by using the elements of the collection c.
c)
HashSet(int It is used to initialize the capacity of the hash set to the given integer value capacity. The capacity grows
capacity) automatically as elements are added to the HashSet.
boolean contains(Object o) It is used to return true if this set contains the specified element.
boolean add(Object o) It is used to adds the specified element to this set if it is not already present.
boolean remove(Object o) It is used to remove the specified element from this set if it is present.
Object clone() It is used to return a shallow copy of this HashSet instance: the elements themselves are not cloned.
Iterator iterator() It is used to return an iterator over the elements in this set.
1. import java.util.*;
2. class Book {
3. int id;
4. String name,author,publisher;
5. int quantity;
6. public Book(int id, String name, String author, String publisher, int quantity) {
7. this.id = id;
8. this.name = name;
9. this.author = author;
10. this.publisher = publisher;
11. this.quantity = quantity;
12. }
13. }
14. public class HashSetExample {
15. public static void main(String[] args) {
16. HashSet<Book> set=new HashSet<Book>();
17. //Creating Books
18. Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
19. Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill",4);
20. Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
21. //Adding Books to HashSet
22. set.add(b1);
23. set.add(b2);
24. set.add(b3);
25. //Traversing HashSet
26. for(Book b:set){
27. System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
28. }
29. }
30. }
Output:
Java TreeSet class implements the Set interface that uses a tree for storage. It inherits AbstractSet class and implements NavigableSet
interface. The objects of TreeSet class are stored in ascending order.
TreeSet() It is used to construct an empty tree set that will be sorted in an ascending order according to the
natural order of the tree set.
TreeSet(Collection c) It is used to build a new tree set that contains the elements of the collection c.
TreeSet(Comparator It is used to construct an empty tree set that will be sorted according to given comparator.
comp)
TreeSet(SortedSet ss) It is used to build a TreeSet that contains the elements of the given SortedSet.
boolean contains(Object o) It is used to return true if this set contains the specified element.
boolean remove(Object o) It is used to remove the specified element from this set if it is present.
void add(Object o) It is used to add the specified element to this set if it is not already present.
void clear() It is used to remove all of the elements from this set.
Object first() It is used to return the first (lowest) element currently in this sorted set.
Object last() It is used to return the last (highest) element currently in this sorted set.
Output:
Ajay
Ravi
Vijay
1. import java.util.*;
2. class Book implements Comparable<Book>{
3. int id;
4. String name,author,publisher;
5. int quantity;
6. public Book(int id, String name, String author, String publisher, int quantity) {
7. this.id = id;
8. this.name = name;
9. this.author = author;
10. this.publisher = publisher;
11. this.quantity = quantity;
12. }
13. public int compareTo(Book b) {
14. if(id>b.id){
15. return 1;
16. }else if(id<b.id){
17. return -1;
18. }else{
19. return 0;
20. }
21. }
22. }
23. public class TreeSetExample {
24. public static void main(String[] args) {
25. Set<Book> set=new TreeSet<Book>();
26. //Creating Books
27. Book b1=new Book(121,"Let us C","Yashwant Kanetkar","BPB",8);
28. Book b2=new Book(233,"Operating System","Galvin","Wiley",6);
29. Book b3=new Book(101,"Data Communications & Networking","Forouzan","Mc Graw Hill",4);
30. //Adding Books to TreeSet
31. set.add(b1);
32. set.add(b2);
33. set.add(b3);
34. //Traversing TreeSet
35. for(Book b:set){
36. System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
37. }
38. }
39. }
Output:
Java HashMap class implements the map interface by using a hashtable. It inherits AbstractMap class and implements Map interface.
HashMap(Map m) It is used to initializes the hash map by using the elements of the given Map object m.
HashMap(int capacity) It is used to initializes the capacity of the hash map to the given integer value, capacity.
HashMap(int capacity, float fillRatio) It is used to initialize both the capacity and fill ratio of the hash map by using its arguments.
Methods of Java HashMap class
Method Description
void clear() It is used to remove all of the mappings from this map.
boolean containsKey(Object key) It is used to return true if this map contains a mapping for the specified key.
boolean containsValue(Object It is used to return true if this map maps one or more keys to the specified value.
value)
boolean isEmpty() It is used to return true if this map contains no key-value mappings.
Object clone() It is used to return a shallow copy of this HashMap instance: the keys and values themselves
are not cloned.
Set entrySet() It is used to return a collection view of the mappings contained in this map.
Set keySet() It is used to return a set view of the keys contained in this map.
Object put(Object key, Object It is used to associate the specified value with the specified key in this map.
value)
int size() It is used to return the number of key-value mappings in this map.
Collection values() It is used to return a collection view of the values contained in this map.
Values before remove: {102=Operating System, 103=Data Communication and Networking, 101=Let us C}
Values after remove: {103=Data Communication and Networking, 101=Let us C}
Output:
1 Details:
101 Let us C Yashwant Kanetkar BPB 8
2 Details:
102 Data Communications & Networking Forouzan Mc Graw Hill 4
3 Details:
103 Operating System Galvin Wiley 6
Next TopicJava LinkedHashMap class
Difference between ArrayList and Vector
ArrayList and Vector both implements List interface and maintains insertion order.
But there are many differences between ArrayList and Vector classes that are given below.
ArrayList Vector
2) ArrayList increments 50% of current array Vector increments 100% means doubles the array size if total number of
size if number of element exceeds from its element exceeds than its capacity.
capacity.
4) ArrayList is fast because it is non- Vector is slow because it is synchronized i.e. in multithreading environment, it
synchronized. will hold the other threads in runnable or non-runnable state until current thread
releases the lock of object.
5) ArrayList uses Iterator interface to traverse Vector uses Enumeration interface to traverse the elements. But it can use
the elements. Iterator also.
1. import java.util.*;
2. class TestArrayList21{
3. public static void main(String args[]){
4.
5. List<String> al=new ArrayList<String>();//creating arraylist
6. al.add("Sonoo");//adding object in arraylist
7. al.add("Michael");
8. al.add("James");
9. al.add("Andy");
10. //traversing elements using Iterator
11. Iterator itr=al.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }
Test it Now
Output:
Sonoo
Michael
James
Andy
1. import java.util.*;
2. class TestVector1{
3. public static void main(String args[]){
4. Vector<String> v=new Vector<String>();//creating vector
5. v.add("umesh");//method of Collection
6. v.addElement("irfan");//method of Vector
7. v.addElement("kumar");
8. //traversing elements using Enumeration
9. Enumeration e=v.elements();
10. while(e.hasMoreElements()){
11. System.out.println(e.nextElement());
12. }
13. }
14. }
Test it Now
Output:
umesh
irfan
kumar