
This tutorial about Java collections is designed for everyone, whether you’re new to programming or already experienced. It’s here to help you really understand collections with real-life examples that are easy to follow, step by step.
In this Java collections framework tutorial, we will cover the following topics in depth.
- What is a Collection in Java?
- Real-life examples of Collections.
- Types of objects stored in a Collection (container).
- Why do we need Collections in Java?
- Understanding the Collections Framework in Java.
- Comparing Arrays and Collections in Java, and much more.
What is Collection in Java:
In Java, a collection is an object that represents a group of other objects as a single unit. it is also known as container object or collection object in java.
Collections in Java contain references to objects. When you add an object to a collection, you’re actually adding a reference that points to the memory location where the actual object is stored.
Real-life example of collections:
A collection in Java is somewhat like a checklist where you keep track record of items. Instead of physically holding the items, you have a list that tells you what items are there and where to find them.
In Java references are used to work with actual data indirectly. Instead of working directly with the data itself, you work with references that point to where the data is stored in memory. this approach saves memory and duplication of data.
Types of objects stored in a Collection:
In Java collections, you can store both homogeneous (objects of the same type) and heterogeneous (objects of different types) collections:
Homogeneous Objects: Homogeneous objects are of the same type. In a collection, all elements are instances of the same class or type. This provides consistency and simplicity. An example is an ArrayList
of integers:
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(5);
numbers.add(10);
numbers.add(15);
Heterogeneous Objects: Heterogeneous objects are of different types. In a collection, elements can be instances of different classes or types. This allows you to mix and match objects with various properties. An example is an ArrayList
that holds different types of objects:
ArrayList<Object> mixed = new ArrayList<>();
mixed.add("Hello");
mixed.add(42);
mixed.add(new CustomObject());
In the “homogeneous” example, all elements are of the Integer
type. In the “heterogeneous” example, the collection holds objects of different types: a string, an integer, and an instance of a custom class.
Why do we need Collections in Java?
“Before we explore the need for collections in Java, let’s take a look at the four ways the Java Virtual Machine (JVM) stores values in a Java application.
1. Using variable approach:
Suppose you want to store one value in the memory then you will create only one variable and assign a value like this: int x = 10;
The purpose of variable x is to store one int value 10. If we want to store two int values, we will create two variables like this:
int a = 10;
int b = 20;
// ... and many more
There is no problem to store until the third or fourth value. But if we want to store 2000 values then declaring 2000 variables in a program is the worst kind of programming practice.
Limitations of the Variable Approach given below:
- Variables can hold only a single value at a time.
- As the number of variables grows, the code becomes harder to read and reuse.
- dealing with many variables, the program’s execution can become slower it will take more time to process
by using the another approach “Class object” we can overcome this issue.
2. Class object approach:
Instead of using separate variables for each piece of information, you create a special container called a “class” to hold related data together. For example, if you’re dealing with students, you can create an student class.
class Student {
int rollNumber;
String name;
}
public class Main {
public static void main(String[] args) {
// Creating class objects to represent students
Student student1 = new Student();
student1.rollNumber = 101;
student1.name = "Alice";
Student student2 = new Student();
student2.rollNumber = 102;
student2.name = "Bob";
}
}
As you add more students, you’ll need to keep creating new objects, leading to inefficient memory usage. With a large number of students, managing so many individual objects becomes unwieldy and memory-intensive.
Issue with Creating Individual Class Objects:
In the given example, you’re creating separate class objects student1
and student2
for each student. While this might work fine for a small number of students, it becomes problematic as your dataset grows:
3. Array object approach:
this approach groups multiple objects into an array, allows you to store and manage a collection of related data items together.
if you want to store 5000 objects of student class into an array. Instead of creating separate variables or objects for each student, you can use an array object to group student data together
Student[] studentArray = new Student[5000];
The advantage of an array is that we can store a huge number of values by using a single variable studentArray and retrieve them easily.
Array helps to improve the code readability but there are several types of problems and limitations with the array. They are as follows:
Limitations of Arrays in Java:
We cannot store different class objects into the same array because an array can store only one data type of elements (objects).
You can only store instances of the Student
class within this array. Attempting to store objects of other classes, like a Customer
object, within the same array will result in a type mismatch error.
Student[] studentArray = new Student[5000]; // Array for student objects
studentArray[0] = new Student("Alice", 1001); // Valid, storing a student
studentArray[1] = new Customer(); // Invalid, trying to store a different type
We can resolve this problem by using an object array. Since an Object
array can store objects of any class, you can store objects from various classes within the same array. because every class in Java is derived from the fundamental Object class.”
For example:
Object[] objectArray = new Object[5000]; // An array of generic objects
objectArray[0] = new Student("Alice", 1001); // Storing a student valid
objectArray[1] = new Customer("Bob"); // Storing a customer valid
objectArray[2] = "Hello, World!"; // Storing a string valid
In this example, you’re storing objects of Student
, Customer
, and String
classes in the same array. it is not recommended due to decreased type safety, increased code complexity, and potential runtime errors.
- Arrays have a fixed size and can’t be changed once created. This means we need to know the size beforehand, which might not always be possible.
- Adding elements to the end of an array is simple, but inserting or removing elements in the middle is complex.
- Sorting elements in an array can be difficult because arrays don’t come with built-in methods for sorting. Collections like TreeSet offer pre-build methods for ready-made sorting elements
Because of these limitations of arrays, programmers seek a better way to manage groups of objects. The solution often lies in using collection objects in Java.
4. Using collection object:
by using collection objects, you can store both similar and different types without any size limitation . In other words, you can store as many elements as you need.
A collection is essentially a container object designed for holding multiple elements. These elements can be of the same type (homogeneous) or different types (heterogeneous).
The collection can contain duplicate elements as well as unique elements, depending on the specific collection type being used.
What is Collections Framework in Java?
Collections Framework is a pre-defined set of classes and interfaces. It is present in java.util package. It allows us to store, retrieve, and update a group of objects.
Collections framework in Java supports mainly two types of containers:
- Collection: it is used to store a collection of elements (objects).
- Map: it is used to store key/value pairs.
Important Interfaces in Collections Framework:
Here are some important interfaces that present in java.util package:
- Collection
- List
- Set
- Map
These interfaces provide different ways of managing groups of objects, depending on the requirements of your application.
List of interfaces present in java.util package:
The list of interfaces defined in java.util package is shown in the below table:
Collection | List | Set | Map | Queue |
Comparator | ListIterator | NavigableSet | SortedSet | Deque |
Iterator | Enumeration | Observer | SortedMap | RandomAccess |
EventListener | Formattable | Map.Entry | NavigableMap |
These interfaces act like shared rules for different collection classes. They make sure all collections work in similar ways. These rules guide how the collections should behave, helping developers work with them in a consistent and predictable way.
List of classes present in java.util package:
The list of important implementation classes present in java.util package is shown in the below table:
AbstractList | FormattableFlags | ResourceBundle |
AbstractMap | Formatter | Scanner |
AbstractQueue | AbstractSequentialList | HashMap |
AbstractSet | HashSet | Stack |
ArrayDeque | Hashtable | StringTokenizer |
LinkedList | ArrayList | Vector |
Collections | EnumMap | EnumSet |
Calender | LinkedHashMap | TreeMap |
The purpose of the pre-built classes in the Java Collection Framework is to provide a set of tools for managing and manipulating collections of data (groups of objects) efficiently and effectively
Difference between arrays and collection in java:
The difference between arrays and collections are given below:
Arrays | Collection | |
1 | Arrays have a fixed size that is determined when they are created. Once the size is set, it cannot be changed without creating a new array. | Collections are grow-able in nature and hence based on our requirement we can increase or decrease the size. |
2 | Arrays can hold both primitive data types and objects. | Collections can hold only objects but not primitive. |
3 | Performance point of view arrays faster than collection | Performance point of view collections are slower than array |
4 | Arrays can hold only homogeneous elements. | Collections can hold both homogeneous and heterogeneous elements. |
5 | Memory point of view arrays are not recommended | Memory point of view collections are recommended to use. |
6 | For any requirement, there is no ready method available. | For every requirement ready made method support is available. |
Advantage of Collections framework in Java:
Organization: The Collection Framework helps you organize your objects in a structured manner. It provides different types of collections like lists, sets, and maps that allow you to store and manage your data efficiently.
Ease of Use: You don’t have to worry about complex data structures and algorithms. The Collection Framework handles all the underlying complexities, making it easy for you to work with collections.
Reusability: The framework is designed in a way that you can reuse its components across different projects.
Flexibility: You can choose the appropriate collection type based on your needs. For example, if you want to maintain a list of elements in a specific order, you can use a List
Memory Efficiency: The framework is designed to manage memory efficiently. It handles memory allocation and deallocation, so you don’t have to worry about memory leaks or manual memory management
Type Safety: The framework provides type safety through the use of generics. This means that you can specify the type of elements a collection will hold, and the compiler will catch type-related errors at compile time, reducing runtime errors.
Conclusion:
“In this tutorial, you have learned about the collections framework in Java through real-time examples. We have covered a wide range of topics related to the collections framework, all explained in simple terms.
I hope you’ve grasped the fundamental definition of collections in Java and found this topic enjoyable. In our next tutorial, we will learn about the collection interface and hierarchy in Java.”