Skip to content

Commit 384b172

Browse files
authored
Wrapper Classes
1 parent ef95d1c commit 384b172

1 file changed

Lines changed: 189 additions & 0 deletions

File tree

section_16/README.md

Lines changed: 189 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,189 @@
1+
# Collections And Wrapper Classes
2+
## Collections
3+
In Java, collections are objects that group multiple elements into a single unit. They provide a way to work with groups of objects, such as lists, sets, maps, queues, etc., and offer various operations for manipulation, traversal, and searching of the elements they contain. Collections framework in Java is part of the Java Collections Framework (JCF), which provides a set of interfaces and classes to represent collections and manipulate them efficiently.
4+
Here are some common types of collections in Java:
5+
- **List :** A list is an ordered collection that allows duplicate elements. Common implementations include ArrayList, LinkedList, and Vector.
6+
7+
- **Set :** A set is a collection that does not allow duplicate elements. Common implementations include HashSet, TreeSet, and LinkedHashSet.
8+
9+
- **Map :** A map is a collection that maps keys to values. Each key must be unique, but the values can be duplicated. Common implementations include HashMap, TreeMap, and LinkedHashMap.
10+
11+
- **Queue :** A queue is a collection used to hold elements before processing. Common implementations include LinkedList (which can act as both a list and a queue) and PriorityQueue.
12+
13+
- **Deque :** A deque (double-ended queue) is a collection that supports insertion and deletion of elements at both ends. Common implementations include ArrayDeque and LinkedList.
14+
15+
Java's collections framework provides several benefits, including type safety, performance, and interoperability between different collections and algorithms. It offers a rich set of APIs for common operations like adding, removing, searching, and iterating over elements, making it easier to work with collections in Java applications.
16+
## Wrapper Classes
17+
In Java, wrapper classes are classes that encapsulate primitive data types into objects. While primitive data types like int, float, double, etc., are basic data types provided by the language, they are not objects and don't have methods associated with them. Wrapper classes provide a way to treat primitive data types as objects and enable additional functionalities like conversion, manipulation, and passing them as arguments to methods that require objects.
18+
19+
Here are the wrapper classes for primitive data types in Java:
20+
**Byte :** `java.lang.Byte`
21+
**Short :** `java.lang.Short`
22+
Integer :** `java.lang.Integer`
23+
**Long :** `java.lang.Long`
24+
**Float :** `java.lang.Float`
25+
**Double :** `java.lang.Double`
26+
**Character :** `java.lang.Character`
27+
**Boolean :** `java.lang.Boolean`
28+
- Each wrapper class provides methods to perform operations on the corresponding primitive data type. For example, you can convert a string representation of a number into an Integer object using methods like `parseInt()` in the Integer class. Similarly, you can convert an Integer object to a primitive int using methods like `intValue()`.
29+
- Wrapper classes are commonly used in scenarios where primitive data types need to be treated as objects, such as collections, generics, and reflection. Additionally, they are useful when dealing with APIs that require objects rather than primitive data types. However, it's important to be mindful of the potential performance overhead associated with using wrapper classes, especially in performance-sensitive applications.
30+
## Boxing
31+
In Java, the valueOf() method is a static method provided by wrapper classes to convert a string representation of the data into an object of the corresponding wrapper class. This method is particularly useful when you have data in string format and need to convert it into an object for further processing. This is called `Boxing` in java.
32+
### Syntax
33+
The syntax of the `valueOf()` method varies slightly depending on the wrapper class, but generally, it follows the format:
34+
```java
35+
WrapperClass.valueOf(String str);
36+
37+
```
38+
Where:
39+
40+
- WrapperClass is the name of the wrapper class (e.g., Integer, Double, Boolean, etc.).
41+
- str is the string representation of the data that you want to convert.
42+
### Converting String to Integer
43+
```java
44+
String str = "123";
45+
Integer intValue = Integer.valueOf(str);
46+
System.out.println("Integer value: " + intValue);
47+
```
48+
In this example:
49+
50+
- We have a string "123".
51+
- We use `Integer.valueOf(str)` to convert the string to an `Integer` object.
52+
- The resulting intValue contains the integer value 123.
53+
### Converting String to Double
54+
```java
55+
String str = "3.14";
56+
Double doubleValue = Double.valueOf(str);
57+
System.out.println("Double value: " + doubleValue);
58+
```
59+
In this example:
60+
61+
- We have a string "3.14".
62+
- We use `Double.valueOf(str)` to convert the string to a `Double object.
63+
- The resulting `doubleValue` contains the double value 3.14.
64+
### Conclusion
65+
The `valueOf()` method in Java is a convenient way to convert string representations of data into objects of the corresponding wrapper classes. It simplifies the process of parsing and converting strings into primitive data types, allowing for easier manipulation and processing of data in Java programs.
66+
## Unboxing
67+
In Java, unboxing refers to the automatic conversion of a wrapper class object to its corresponding primitive data type. When you retrieve the value from a wrapper class object, Java automatically unboxes it to its primitive type. This process simplifies code and improves readability by allowing you to work with primitive types in situations where wrapper class objects are used.
68+
### Unboxing Process
69+
Unboxing occurs implicitly when you assign a wrapper class object to a primitive type variable or when you use the value of a wrapper class object in an expression that expects a primitive type.
70+
#### Example
71+
```java
72+
Integer wrapperInt = Integer.valueOf(10); // Creating an Integer wrapper object
73+
int primitiveInt = wrapperInt; // Unboxing the Integer to int
74+
```
75+
In this example:
76+
77+
- wrapperInt is an `Integer` object containing the value 10.
78+
- primitiveInt is an int variable.
79+
- When wrapperInt is assigned to primitiveInt, Java automatically unboxes the Integer object to its corresponding int value.
80+
### Example Usage
81+
```java
82+
Integer wrapperInt = Integer.valueOf(20);
83+
int primitiveInt = wrapperInt; // Unboxing
84+
85+
Double wrapperDouble = Double.valueOf(3.14);
86+
double primitiveDouble = wrapperDouble; // Unboxing
87+
88+
Boolean wrapperBoolean = Boolean.valueOf(true);
89+
boolean primitiveBoolean = wrapperBoolean; // Unboxing
90+
```
91+
In each of these examples, the value of the wrapper class object is automatically unboxed to its corresponding primitive type.
92+
### Benefits of Unboxing
93+
**Simplifies Code :** Unboxing eliminates the need for explicit conversion between wrapper class objects and primitive types, making the code cleaner and more concise.
94+
**Improves Readability :** Unboxing makes the code easier to understand by allowing you to work with primitive types directly, especially in situations where wrapper class objects are used, such as collections and generics.
95+
### Conclusion
96+
Unboxing in Java simplifies the process of converting wrapper class objects to their corresponding primitive types. By allowing you to work seamlessly with primitive types and wrapper class objects, unboxing improves code readability and makes Java programming more efficient.
97+
## Autoboxing and Auto-Unboxing in Java
98+
Autoboxing and auto-unboxing are features introduced in Java 5 that simplify the conversion between primitive data types and their corresponding wrapper classes. Autoboxing automatically converts primitive types to wrapper objects when necessary, while auto-unboxing automatically converts wrapper objects to their corresponding primitive types.
99+
### Autoboxing
100+
Autoboxing is the process of automatically converting primitive data types into their corresponding wrapper classes. This conversion is done implicitly by the Java compiler.
101+
#### Example
102+
```java
103+
// Autoboxing int to Integer
104+
int primitiveInt = 10;
105+
Integer wrapperInt = primitiveInt; // Autoboxing
106+
```
107+
In this example, the primitive `int` value 10 is automatically converted to an Integer wrapper class object.
108+
### Auto-Unboxing
109+
Auto-unboxing is the process of automatically converting wrapper class objects to their corresponding primitive data types. This conversion is also done implicitly by the Java compiler.
110+
#### Example
111+
```java
112+
// Auto-unboxing Integer to int
113+
Integer wrapperInt = Integer.valueOf(20);
114+
int primitiveInt = wrapperInt; // Auto-unboxing
115+
```
116+
In this example, the `Integer` wrapper class object containing the value 20 is automatically converted to a primitive int.
117+
#### Benefits of Autoboxing and Auto-Unboxing
118+
- **Simplifies Code :** Autoboxing and auto-unboxing eliminate the need for explicit conversion between primitive types and wrapper classes, making the code cleaner and more concise.
119+
- **Improves Readability :** These features make Java code more readable by allowing developers to work with primitive types and wrapper classes interchangeably, without having to manually perform conversions.
120+
#### Considerations
121+
- **Performance :** While autoboxing and auto-unboxing provide convenience, they may introduce performance overhead compared to manually handling conversions, especially in performance-sensitive code.
122+
- **Null Handling :** Auto-unboxing a null wrapper object will result in a NullPointerException.
123+
#### Conclusion
124+
Autoboxing and auto-unboxing in Java simplify the process of converting between primitive types and their corresponding wrapper classes. By automatically handling these conversions, these features improve code readability and make Java programming more convenient. However, developers should be mindful of performance implications and null handling when using autoboxing and auto-unboxing in their code.
125+
## Caching with valueOf()
126+
In Java, the `valueOf()` method provided by wrapper classes such as Integer, Double, Boolean, etc., often implements caching for certain commonly used values. This caching mechanism improves memory utilization and performance by reusing existing objects for frequently accessed values within a predefined range.
127+
### Caching Mechanism
128+
When you call the `valueOf()` method for certain primitive values within a specific range, the wrapper class implementation may return a cached object instead of creating a new one. This optimization is particularly useful for frequently used values, such as small integers.
129+
#### Example
130+
```java
131+
Integer int1 = Integer.valueOf(10);
132+
Integer int2 = Integer.valueOf(10);
133+
134+
```
135+
In this example, both int1 and int2 will reference the same cached Integer object representing the value 10. Instead of creating a new object for each call to valueOf(10), Java reuses the existing cached object.
136+
### Benefits of Caching
137+
- **Memory Efficiency :** Caching reduces memory consumption by reusing existing objects for commonly used values, rather than creating new objects for each value.
138+
- **Improved Performance :** By reusing cached objects, Java avoids unnecessary object creation and garbage collection overhead, resulting in improved performance, especially in scenarios where the same values are used frequently.
139+
### Considerations
140+
- **Range Limitation :** Caching is typically implemented for values within a predefined range. Values outside this range may not be cached and will result in the creation of new objects.
141+
- **Thread Safety :** While caching improves performance, developers should ensure thread safety when working with mutable wrapper classes in a multi-threaded environment.
142+
### Conclusion
143+
Caching with `valueOf()` in Java improves memory efficiency and performance by reusing existing objects for commonly used values. By avoiding unnecessary object creation and leveraging cached objects, Java programs can achieve better memory utilization and faster execution, particularly in scenarios involving frequently accessed values. Developers should be aware of the caching behavior of wrapper classes and leverage it effectively to optimize their code.
144+
## Java Collection Hierarchy Framework
145+
The Java Collection Framework provides a unified architecture for representing and manipulating collections of objects. It includes interfaces, implementations, and algorithms to manage collections of objects efficiently. Understanding the collection hierarchy is essential for Java developers to utilize the appropriate collection types for their specific needs.
146+
### Interfaces
147+
#### 1. Collection
148+
- Represents a group of objects known as elements.
149+
- **Subinterfaces :** List, Set, and Queue.
150+
#### 2. List
151+
- Ordered collection (by index).
152+
- Allows duplicate elements.
153+
- **Subinterfaces :** ArrayList, LinkedList, Vector, Stack, etc.
154+
#### 3. Set
155+
- Collection that does not allow duplicate elements.
156+
- **Subinterfaces :** HashSet, LinkedHashSet, TreeSet.
157+
#### 4. Queue
158+
- Collection used to hold elements before processing.
159+
- Follows FIFO (First-In-First-Out) order.
160+
- **Subinterfaces :** Deque, PriorityQueue.
161+
#### 5. Map
162+
- Represents a mapping between keys and values.
163+
- Does not extend the Collection interface.
164+
- **Subinterfaces :** HashMap, LinkedHashMap, TreeMap.
165+
### Classes
166+
#### 1. ArrayList
167+
- Resizable array implementation of the List interface.
168+
- Allows fast random access but slower insertion/deletion at the middle.
169+
#### 2. LinkedList
170+
- Doubly-linked list implementation of the List interface.
171+
- Efficient for insertion/deletion at the beginning/middle.
172+
#### 3. HashSet
173+
- Implements the Set interface using a hash table.
174+
- Does not guarantee the order of elements.
175+
#### 4. TreeSet
176+
- Implements the Set interface using a Red-Black tree.
177+
- Maintains elements in sorted order.
178+
#### 5. HashMap
179+
- Implements the Map interface using a hash table.
180+
- Provides constant-time performance for basic operations (get and put).
181+
#### 6. TreeMap
182+
- Implements the Map interface using a Red-Black tree.
183+
- Maintains elements in sorted order based on keys.
184+
### Benefits
185+
**Standardized API :** Provides a common set of interfaces and classes for working with collections, promoting code reusability and interoperability.
186+
**Efficiency :** Offers efficient implementations for various collection types, catering to different use cases and performance requirements.
187+
**Flexibility :** Supports a wide range of operations and provides different implementations to suit specific application needs.
188+
### Conclusion
189+
The Java Collection Hierarchy Framework is a powerful tool for managing collections of objects in Java programs. By understanding its interfaces, classes, and their relationships, developers can effectively utilize collections to store, manipulate, and retrieve data efficiently. Whether working with lists, sets, queues, or maps, the Collection Framework provides a rich set of features to meet the diverse needs of Java applications.

0 commit comments

Comments
 (0)