0% found this document useful (0 votes)
3 views19 pages

Java Collections

The Java Collections API provides a framework for managing groups of objects, offering classes and interfaces for lists, maps, and sets. Arrays are fixed in size and can only hold homogeneous data types, while collections are dynamic and can accommodate both homogeneous and heterogeneous objects. The document outlines the differences between arrays and collections, the hierarchy of collection interfaces, and various utility methods available in the Java Collections class.

Uploaded by

Sagar Sharma
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)
3 views19 pages

Java Collections

The Java Collections API provides a framework for managing groups of objects, offering classes and interfaces for lists, maps, and sets. Arrays are fixed in size and can only hold homogeneous data types, while collections are dynamic and can accommodate both homogeneous and heterogeneous objects. The document outlines the differences between arrays and collections, the hierarchy of collection interfaces, and various utility methods available in the Java Collections class.

Uploaded by

Sagar Sharma
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

Java Collections

The Java Collections API provide Java developers with a set of classes and interfaces that
makes it easier to work with collections of objects, e.g. lists, maps, stacks etc.

Rather than having to write your own collection classes, Java provides these ready-to-
use collection classes for you.

Array :

1. An array is an indexed collection of fixed no of homogeneous data elements.

2. An array represents a group of elements of same data type.

3. The main advantage of array is we can represent huge no of elements by using single variable. So that
readability of the code will be improved.

 Example Without Arrays


int mark1 = 90;
int mark2 = 85;
int mark3 = 92;
int mark4 = 78;
int mark5 = 88;
 Example Without Arrays

int[] mark = {90,85,92,78,88};

Limitation of Object[] array :


1. Arrays are fixed in size that is once we created an array there is no chance of increasing (or)
decreasing the size based on our requirement hence to use arrays concept compulsory we should know
the size in advance which may not possible always.

2. Arrays can hold only homogeneous data elements.

Student[] s = new Student[10000]; // Array to hold Student objects


s[0] = new Student(); // Valid, because Student is the correct type
s[1] = new Customer(); // Invalid, results in a compile-time error

3) But we can resolve this problem by using object type array(Object[]).


// Create an array of type Object
Object[] o = new Object[10000];

// Store a Student object in the array


o[0] = new Student("Alice", 20);

// Store a Customer object in the array


o[1] = new Customer("C123", "123 Main St");

// Access and print the elements


[Link](o[0]); // Prints Student object
[Link](o[1]); // Prints Customer object
4) Arrays concept is not implemented based on some data structure hence ready-made methods
support we can't expert. For every requirement we have to write the code explicitly.

To overcome the above limitations we should go for collections concept.

1. Collections are growable in nature that is based on our requirement we can increase (or) decrease the
size hence memory point of view collections concept is recommended to use.

2. Collections can hold both homogeneous and heterogeneous objects.

3. Every collection class is implemented based on some standard data structure hence for every
requirement ready-made method support is available being a programmer we can use these methods
directly without writing the functionality on our own.
ArrayList<Object> list = new ArrayList<>();
[Link](new Student("Alice", 20));
[Link](new Customer("C123", "123 Main St"));

Differences between Arrays and Collections ?

ARRAYS COLLECTIONS
1) Fixed in size. 1. Collections are growable in nature.
2) Memory point of view arrays are not 2. Memory point of view collections are
recommended to use. highly recommended to use.
3) Performance point of view arrays are 3. Performance point of view collections are
recommended to use not recommended to use.
4) Arrays can hold only homogeneous data type 4. Collections can hold both homogeneous
elements. and heterogeneous elements.
5) There is no underlying data structure for 5. Every collection class is implemented
arrays and hence there is no readymade based on some standard data structure
method support. and hence readymade method support is
available.
6) Arrays can hold both primitives and object 6. Collections can hold only objects but not
types. primitives.

Collection:
If we want to represent a group of objects as single entity then we should go for collections.

Collection framework:

It defines several classes and interfaces to represent a group of objects as a single entity.

Java Collection Core Classes and Interfaces :

The core interfaces of the Java Collection API are:

 Java Collection
 Java List
 Java Set
 Java SortedSet
 Java navigableSet
 Java Map
 Java SortedMap
 Java NavigableMap
 Java Queue

Collection
1. If we want to represent a group of "individual objects" as a single entity then we should go for
collection.
2. In general we can consider collection as root interface of entire collection framework.

3. Collection interface defines the most common methods which can be applicable for any collection
object.

4. There is no concrete class which implements Collection interface directly.

See Example Student :

JAVA COLLECTION HIERARCHY

List :
1. It is the child interface of Collection.

2. If we want to represent a group of individual objects as a single entity where "duplicates are allow and
insertion order must be preserved" then we should go for List interface
SET :
1. It is the child interface of Collection.

2. If we want to represent a group of individual objects as single entity "where duplicates are not allow
and insertion order is not preserved" then we should go for Set interface.
SORTED SET :
1. It is the child interface of Set.

2. If we want to represent a group of individual objects as single entity "where duplicates are not allow
but all objects will be insertion according to some sorting order then we should go for SortedSet. (or)

3. If we want to represent a group of "unique objects" according to some sorting order then we should
go for SortedSet.

NavigableSet:

1. It is the child interface of SortedSet.

2. It provides several methods for navigation purposes.

Queue:

1. It is the child interface of Collection.

2. If we want to represent a group of individual objects prior to processing then we should go for queue
concept
Note: All the above interfaces (Collection, List, Set, SortedSet, NavigableSet, and Queue) meant for
representing a group of individual objects. If we want to represent a group of objects as key-value pairs
then we should go for Map.

Map:

1. Map is not child interface of Collection.

2. If we want to represent a group of objects as key-value pairs then we should go for Map interface.

3. Duplicate keys are not allowed but values can be duplicated.

SortedMap:

1. It is the child interface of Map.


2. If we want to represent a group of objects as key value pairs "according to some sorting order of keys"
then we should go for SortedMap.

NavigableMap:

1) It is the child interface of SortedMap and defines several methods for navigation purposes.

Java Collections Class :


 addAll()
 binarySearch()
 copy()
 reverse()
 shuffle()
 sort()
 copy()
 min()
 max()
 replaceAll()
 unmodifiableSet()

The Java Collections class, [Link], contains a long list of utility methods for
working with collections in Java. In this Collections class tutorial I will go through some
of the most useful of these methods.

addAll()

The Java Collections addAll() method can add a variable number of elements to
a Collection (typically either a List or a Set . Here is a java code example of calling
the Collections addAll() method:

List<String> list = new ArrayList<>();

[Link](list, "element 1", "element 2", "element 3");


binarySearch()

The Collections binarySearch() method can search a Java List for an element using a binary search
algorithm. The List must be sorted in ascending order before you search it using binarySearch() . See the
tutorial about sorting Java Lists for more information about how to sort a List in ascending order. Here is
an example of searching a List using the Collections binarySearch() method:

copy()

The Collections copy() method can copy all elements of a List into another List. Here is a Java
example of calling the Collections copy() method:

List<String> source = new ArrayList<>();


[Link](source, "e1", "e2", "e3");

List<String> destination = new ArrayList<>();


[Link](destination, source);

reverse()

The Collections reverse() method can reverse the elements in a Java List.
Here is an example of reversing the elements of a List:

List>String< list = new ArrayList<String>();

[Link]("one");
[Link]("two");
[Link]("three");

[Link](list);

After executing the above code, the sequence of the elements in the List will
be three, two, one .
shuffle()

The Collections shuffle() method can shuffle the elements of a List. Here is an example of
shuffling a list with the Collections shuffle() method:

List>String< list = new ArrayList<String>();

[Link]("one");
[Link]("two");
[Link]("three");

[Link](list);

sort()

The Collections sort() method can sort a Java [Link] is an example of sorting a
Java List using Collections sort() method:

List>String< list = new ArrayList<String>();

[Link]("one");
[Link]("two");
[Link]("three");
[Link]("four");

[Link](list);

After running this code the order of the elements in the List will be four, one, three, four, as
the String elements will be sorted alphabetically.

min()

The Collections min() method can find the minimum element in a List according to the
natural ordering of the elements (see my Java List sorting tutorial). Here is an example
of finding the minimum element in a Java List using Collections min() method:

List source = new ArrayList();


[Link]("1");
[Link]("2");
[Link]("3");
String min = (String) [Link](source);

After running the code above, the min variable will contain the String value 1 .

max()

The Collections max() method can find the maximum element in a List according to the
natural order of the elements. Here is an example of finding the maximum element in a
Java List:

List source = new ArrayList();


[Link]("1");
[Link]("2");
[Link]("3");

String max = (String) [Link](source);

After running the code above, the max variable will contain the String value 3 .

replaceAll()

The Java Collections replaceAll() method can replace all occurrences of one
element with another element. You pass the element to replace and the element
to replace it with as parameters to the replaceAll() method.
The Collections replaceAll() method returns true if any elements were replaced,
and false if not. Here is an example of replacing all occurrences of one element
with another in a Java List:

List source = new ArrayList();


[Link]("A");
[Link]("B");
[Link]("A");

boolean replacedAny = [Link](source, "A", "C");

After executing this example, the source List will contain the elements C, B and C.
The replacedAny variable will contain the value true because at least one element
was replaced in the List.
The Collections replaceAll() method uses the equals() method of each element
to determine if the element is equal to the element to replace or not. I have a
written a few more details about how the equals() method works in my section
about the Java equals() method.

unmodifiableSet()

The unmodifiableSet() method in the Java Collections class can create an


immutable (unmodifiable) Set from a normal Java Set . Here is a Java example
of creating an immutable Set from a normal Set:

Set normalSet = new HashSet();

Set immutableSet = [Link](normalSet);

What is the difference between Collection and Collections ?

"Collection is an "interface" which can be used to represent a group of objects as a

single entity. Whereas "Collections is an utility class" present in [Link] package to

define several utility methods for Collection objects.

Collection--------------------interface

Collections------------------class
Collection interface:

The Java Collection interface ([Link]) is one of the root interfaces of the Java Collection API.
Though you do not instantiate a Collection directly, but rather a subtype of Collection, you may often
treat these subtypes uniformly as a Collection.

If we want to represent a group of individual objects as a single entity then we should go for Collection
interface. This interface defines the most common general methods which can be applicable for any
Collection object.
The following is the list of methods present in Collection interface.

1. boolean add(Object o);

2. boolean addAll(Collection c);

3. boolean remove(Object o);

4. boolean removeAll(Object o);

5. boolean retainAll(Collection c); To remove all objects except those present in c.

6. Void clear();

7. boolean contains(Object o);

8. boolean containsAll(Collection c);

9. boolean isEmpty();

10. Int size();

11. Object[] toArray();

Create a Collection

As just mentioned above, you do not create a Collection instance directly, but an instance of
one of the subtypes of Collection. Here is an example of creating a List which is a subtype
of Collection:

Collection collection = new ArrayList();

The above example works for every subtype of Collection.

Collection Subtypes

The following interfaces (collection types) extends the Java Collection interface:

 List
 Set
 SortedSet
 NavigableSet
 Queue
 Deque
Java does not come with a usable implementation of the Collection interface, so you will have
to use one of the listed subtypes. The Collection interface just defines a set of methods
(behaviour) that each of these Collection subtypes share. This makes it possible ignore what
specific type of Collection you are using, and just treat it as a Collection. This is standard
inheritance, so there is nothing magical about, but it can still be a nice feature from time to
time. Later sections in this text will describe the most used of these common operations.

Here is a method that operates on a Collection:

public class MyCollectionUtil{

public static void doSomething(Collection collection) {

Iterator iterator = [Link]();


while([Link]()){
Object object = [Link]();

//do something to object here...


}
}
}

And here are a few ways to call this method with different Collection subtypes:

Set set = new HashSet();


List list = new ArrayList();

[Link](set);
[Link](list);

Add Element to Collection

Regardless of what Collection subtype you are using there are a few standard methods to add
elements to a Collection. Adding an element to a Collection is done via the add() method. Here
is an example of adding an element to a Java Collection:

String anElement = "an element";


Collection collection = new HashSet();

boolean didCollectionChange = [Link](anElement);


The add() method adds the given element to the collection, and returns true if
the Collection changed as a result of calling the add() method. A Set for instance may not have
changed. If the Set already contained that element, it is not added again. On the other hand, if
you called add() on a List and the List already contained that element, the element would then
exist twice in the List.

Remove Element From Collection

The remove() method removes the given element from the Collection and returns true if the
removed element was present in the Collection, and was removed. If the element was not
present, the remove() method returns false. Here is an example of removing an element from a
Java Collection:

boolean wasElementRemoved = [Link]("an element");

Add Collection of Objects to Collection

You can also add a collection of objects to a Java Collection using the addAll(). Here is an
example of adding a collection of objects to a Java Collection:

Set aSet = ... // get Set with elements from somewhere

Collection collection = new HashSet();

[Link](aSet); //returns boolean too, but ignored here

The Java Collection addAll() adds all elements found in the Collection passed as parameter to
the method. The Collection object itself is not added. Only its elements. If you had
called add() with the Collection as parameter instead, the Collection object itself would have
been added, not its elements.

Exactly how the addAll() method behaves depends on the Collection subtype. Some Collection
subtypes allows the same element to be added more than once, and others don't.

Remove Collection of Elements From Collection

The Java Collection removeAll() removes all elements found the Collection passed as parameter
to the method. If the Collection parameter contains any elements not found the target
collection, these are just ignored. Here is an example of removing a collection of elements from
a Java Collection:

Collection objects = //... get a collection of objects from somewhere.

[Link](objects);

Retain All Elements From a Collection in Another Collection

The Java Collection retainAll() does the opposite of removeAll(). Instead of removing all the
elements found in the parameter Collection, it keeps all these elements, and removes all other
elements. Keep in mind, that only if the elements were already contained in the target
collection, are they retained. Any new elements found in the parameter Collection which are
not in the target collection, are not automatically added. They are just ignored. Here is an
example of retaining all elements from one Colletion in another Java Collection:

Collection colA = new ArrayList();


Collection colB = new ArrayList();

[Link]("A");
[Link]("B");
[Link]("C");

[Link]("1");
[Link]("2");
[Link]("3");

Collection target = new HashSet();

[Link](colA); //target now contains [A,B,C]


[Link](colB); //target now contains [A,B,C,1,2,3]

[Link](colB); //target now contains [1,2,3]

Checking if a Collection Contains a Certain Element

The Collection interface has two methods to check if a Collection contains one or more certain
elements. These are the contains() and containsAll() methods. They are illustrated here:
Collection collection = new HashSet();
boolean containsElement = [Link]("an element");

Collection elements = new HashSet();


boolean containsAll = [Link](elements);

contains() returns true if the collection contains the element, and false if not.

containsAll() returns true if the collection contains all the elements in the parameter collection,
and false if not.

Collection Size

You can check the size of a collection using the size() method. By "size" is meant the number of
elements in the collection. Here is an example:

int numberOfElements = [Link]();

Iterate a Collection

You can iterate all elements of a collection. This is done by obtaining an Java Iterator from the
collection, and iterate through that. Here is how it looks:

Collection collection = new HashSet();


//... add elements to the collection

Iterator iterator = [Link]();


while([Link]()){
Object object = [Link]();
[Link](object);
}

You can also iterate a Java Collection using the Java for-each loop :

Collection collection = new HashSet();


[Link]("A");
[Link]("B");
[Link]("C");

for(Object object : collection) {


[Link](object);
}

List interface:
It is the child interface of Collection.

 If we want to represent a group of individual objects as a single entity where duplicates are allow and
insertion order is preserved. Then we should go for List.

 We can differentiate duplicate objects and we can maintain insertion order by means of index hence
"index play very important role in List".

List interface defines the following specific methods.

1. boolean add(int index,Object o);

2. boolean addAll(int index,Collectio c);

3. Object get(int index);

4. Object remove(int index);

5. Object set(int index,Object new);//to replace

6. Int indexOf(Object o); Returns index of first occurrence of "o".

7. Int lastIndexOf(Object o);

8. ListIterator listIterator();

You might also like