Using wrappers in java

Using wrappers in java

  • Introduction to Java
  • The complete History of Java Programming Language
  • C++ vs Java vs Python
  • How to Download and Install Java for 64 bit machine?
  • Setting up the environment in Java
  • How to Download and Install Eclipse on Windows?
  • JDK in Java
  • How JVM Works – JVM Architecture?
  • Differences between JDK, JRE and JVM
  • Just In Time Compiler
  • Difference between JIT and JVM in Java
  • Difference between Byte Code and Machine Code
  • How is Java platform independent?
  • Decision Making in Java (if, if-else, switch, break, continue, jump)
  • Java if statement with Examples
  • Java if-else
  • Java if-else-if ladder with Examples
  • Loops in Java
  • For Loop in Java
  • Java while loop with Examples
  • Java do-while loop with Examples
  • For-each loop in Java
  • Continue Statement in Java
  • Break statement in Java
  • Usage of Break keyword in Java
  • return keyword in Java
  • Object Oriented Programming (OOPs) Concept in Java
  • Why Java is not a purely Object-Oriented Language?
  • Classes and Objects in Java
  • Naming Conventions in Java
  • Java Methods
  • Access Modifiers in Java
  • Java Constructors
  • Four Main Object Oriented Programming Concepts of Java
  • Inheritance in Java
  • Abstraction in Java
  • Encapsulation in Java
  • Polymorphism in Java
  • Interfaces in Java
  • ‘this’ reference in Java
Читайте также:  Вялые питоны эскиз шеврона

Источник

Wrapper Implementations

Wrapper implementations delegate all their real work to a specified collection but add extra functionality on top of what this collection offers. For design pattern fans, this is an example of the decorator pattern. Although it may seem a bit exotic, it’s really pretty straightforward.

These implementations are anonymous; rather than providing a public class, the library provides a static factory method. All these implementations are found in the Collections class, which consists solely of static methods.

Synchronization Wrappers

The synchronization wrappers add automatic synchronization (thread-safety) to an arbitrary collection. Each of the six core collection interfaces — Collection , Set , List , Map , SortedSet , and SortedMap — has one static factory method.

public static Collection synchronizedCollection(Collection c); public static Set synchronizedSet(Set s); public static List synchronizedList(List list); public static Map synchronizedMap(Map m); public static SortedSet synchronizedSortedSet(SortedSet s); public static SortedMap synchronizedSortedMap(SortedMap m);

Each of these methods returns a synchronized (thread-safe) Collection backed up by the specified collection. To guarantee serial access, all access to the backing collection must be accomplished through the returned collection. The easy way to guarantee this is not to keep a reference to the backing collection. Create the synchronized collection with the following trick.

List list = Collections.synchronizedList(new ArrayList());

A collection created in this fashion is every bit as thread-safe as a normally synchronized collection, such as a Vector .

In the face of concurrent access, it is imperative that the user manually synchronize on the returned collection when iterating over it. The reason is that iteration is accomplished via multiple calls into the collection, which must be composed into a single atomic operation. The following is the idiom to iterate over a wrapper-synchronized collection.

Читайте также:  Php переменные в запросе select

Collection c = Collections.synchronizedCollection(myCollection); synchronized(c)

If an explicit iterator is used, the iterator method must be called from within the synchronized block. Failure to follow this advice may result in nondeterministic behavior. The idiom for iterating over a Collection view of a synchronized Map is similar. It is imperative that the user synchronize on the synchronized Map when iterating over any of its Collection views rather than synchronizing on the Collection view itself, as shown in the following example.

Map m = Collections.synchronizedMap(new HashMap()); . Set s = m.keySet(); . // Synchronizing on m, not s! synchronized(m)

One minor downside of using wrapper implementations is that you do not have the ability to execute any noninterface operations of a wrapped implementation. So, for instance, in the preceding List example, you cannot call ArrayList ‘s ensureCapacity operation on the wrapped ArrayList .

Unmodifiable Wrappers

Unlike synchronization wrappers, which add functionality to the wrapped collection, the unmodifiable wrappers take functionality away. In particular, they take away the ability to modify the collection by intercepting all the operations that would modify the collection and throwing an UnsupportedOperationException . Unmodifiable wrappers have two main uses, as follows:

  • To make a collection immutable once it has been built. In this case, it’s good practice not to maintain a reference to the backing collection. This absolutely guarantees immutability.
  • To allow certain clients read-only access to your data structures. You keep a reference to the backing collection but hand out a reference to the wrapper. In this way, clients can look but not modify, while you maintain full access.

Like synchronization wrappers, each of the six core Collection interfaces has one static factory method.

public static Collection unmodifiableCollection(Collection c); public static Set unmodifiableSet(Set s); public static List unmodifiableList(List list); public static Map unmodifiableMap(Map m); public static SortedSet unmodifiableSortedSet(SortedSet s); public static SortedMap unmodifiableSortedMap(SortedMap m);

Checked Interface Wrappers

The Collections.checked interface wrappers are provided for use with generic collections. These implementations return a dynamically type-safe view of the specified collection, which throws a ClassCastException if a client attempts to add an element of the wrong type. The generics mechanism in the language provides compile-time (static) type-checking, but it is possible to defeat this mechanism. Dynamically type-safe views eliminate this possibility entirely.

Источник

Using wrapper classes in Java

Learn Algorithms and become a National Programmer

A Wrapper class is a class whose object contains a primitive data types. We can think this as a primitive data type with an additional layer which enables it is get benefits of a custom user defined objects in Java.

Why we need Wrapper Classes?

  1. Methods cannot modify data of primitive data types which have been passed an arguments. To do this, we need to use a wrapper class over the primitive data type.
  2. The classes in java.util package handles only objects and hence wrapper classes help in converting primitive types to objects and hence, use the utilities
  3. Data structures in the Collection framework, such as ArrayList and Vector, store only objects and not primitive types.
  4. Only an object can support synchronization in multithreading.

Syntax

Consider a class named prev_class which can be a primitive datatype like int as well. To wrap it in a wrapper class, we create a new class with any valid name like new_class like:

Example of wrapping an int:

Following this, we can create objects and set new data like:

int_wrapper int_object(); int_object.data = 1; int_object.set_data(2); 

In-built wrapper classes

The seven classes of java.lang package are known as wrapper classes in java. The list of seven wrapper classes are given below:

Autoboxing and Unboxing

As we know, Java automatically converts between datatypes to minimize the loss in accuracy. In this process, we have different rules for conversion of supported wrapper classes like Integer.

The two type of conversions are:

Automatic conversion of primitive types to the object of their corresponding wrapper classes is known as autoboxing. For example – conversion of int to Integer, long to Long, double to Double etc.

// Java program to demonstrate Autoboxing public class WrapperExample1 < public static void main(String args[])< //Converting int into Integer int a=21; Integer i=Integer.valueOf(a);//converting int into Integer Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internally System.out.println(a+" "+i+" "+j); >> 

Unboxing: It is just the reverse process of autoboxing. Automatically converting an object of a wrapper class to its corresponding primitive type is known as unboxing. For example – conversion of Integer to int, Long to long, Double to double etc.

// Java program to demonstrate Unboxing public class WrapperExample2 < public static void main(String args[])< //Converting Integer to int Integer a=new Integer(5); int i=a.intValue();//converting Integer to int int j=a;//unboxing, now compiler will write a.intValue() internally System.out.println(a+" "+i+" "+j); >> 

Implemetation

Following implementation demonstrates autoboxing and unboxing:

// Java program to demonstrate Wrapping and UnWrapping // in Java Classes class AutoBoxingUnBoxing < public static void main(String args[]) < // byte data type byte a = 1; // wrapping around Byte object Byte byteobj = new Byte(a); // int data type int b = 11; //wrapping around Integer object Integer intobj = new Integer(b); // float data type float c = 11.6f; // wrapping around Float object Float floatobj = new Float(c); // double data type double d = 251.5; // Wrapping around Double object Double doubleobj = new Double(d); // char data type char e='a'; // wrapping around Character object Character charobj=e; // printing the values from objects System.out.println("Values of Wrapper objects (printing as objects)"); System.out.println("Byte object byteobj: " + byteobj); System.out.println("Integer object intobj: " + intobj); System.out.println("Float object floatobj: " + floatobj); System.out.println("Double object doubleobj: " + doubleobj); System.out.println("Character object charobj: " + charobj); // objects to data types (retrieving data types from objects) // unwrapping objects to primitive data types byte bv = byteobj; int iv = intobj; float fv = floatobj; double dv = doubleobj; char cv = charobj; // printing the values from data types System.out.println("Unwrapped values (printing as data types)"); System.out.println("byte value, bv: " + bv); System.out.println("int value, iv: " + iv); System.out.println("float value, fv: " + fv); System.out.println("double value, dv: " + dv); System.out.println("char value, cv: " + cv); >> 
Values of Wrapper objects (printing as objects) Byte object byteobj: 1 Integer object intobj: 11 Float object floatobj: 11.6 Double object doubleobj: 251.5 Character object charobj: a Unwrapped values (printing as data types) byte value, bv: 1 int value, iv: 11 float value, fv: 11.6 double value, dv: 251.5 char value, cv: a 

Using with Collection Objects

Sometimes you must use wrapper classes, for example when working with Collection objects, such as ArrayList , where primitive types cannot be used (the list can only store objects):

ArrayList myNumbers = new ArrayList(); // Invalid ArrayList myNumbers = new ArrayList(); // Valid 

Utility Methods of Wrapper Classes

Since you’re now working with objects, you can use certain methods to get information about the specific object.

For example, the following methods are used to get the value associated with the corresponding wrapper object: intValue() , byteValue() , shortValue() , longValue() , floatValue() , doubleValue() , charValue() , booleanValue() .

This example will output the same result as the example above:

Another useful method is the toString() method, which is used to convert wrapper objects to strings.

In the following example, we convert an Integer to a String, and use the length() method of the String class to output the length of the «string»:

Primitive Wrapper Classes are Immutable in Java

Consider below Java program.

// Java program to demonstrate that prmitive // wrapper classes are immutable class Wrapper < public static void main(String[] args) < Integer i = new Integer(14); System.out.println(i); modify(i); System.out.println(i); >private static void modify(Integer i) < i = i + 1; >> 

The parameter i is reference in modify and refers to same object as i in main(), but changes made to i are not reflected in main(), why?

Explanation:

All primitive wrapper classes (Integer, Byte, Long, Float, Double, Character, Boolean and Short) are immutable in Java, so operations like addition and subtraction create a new object and not modify the old.

The below line of code in the modify method is operating on wrapper class Integer, not an int

  • Unwrapping i to an int value
  • Add 1 to that value
  • Wrapping the result into another Integer object
  • Assign the resulting Integer to i

Since object references are passed by value, the action taken in the modify method does not change i that was used as an argument in the call to modify. Thus the main routine still prints 14 after the method returns.

Comparison of Autoboxed Integer objects

When we assign an integer value to an Integer object, the value is autoboxed into an Integer object. For example the statement “Integer x = 1” creates an object ‘x’ with value 1.

Following are some interesting output questions based on comparison of Autoboxed Integer objects.

Predict the output of following Java Program

Since x and y refer to different objects, we get the output as “Not Equal”

The output of following program is a surprise from Java.

In Java, values from -128 to 127 are cached, so the same objects are returned. The implementation of valueOf() uses cached objects if the value is between -128 to 127.

If we explicitly create Integer objects using new operator, we get the output as “Not Same”. See the following Java program. In the following program, valueOf() is not used.

Predict the output of the following program.

Explanation: Two objects will be created here. First object which is pointed by X due to calling of new operator and second object will be created because of Auto-boxing.

Parth Maniyar

Parth Maniyar

Competitive Programmer | Intern at OpenGenus | Bachelor of Technology (2017 to 2021) in Information Technology at Ahmedabad University

OpenGenus Tech Review Team

Software Engineering

Find height or depth of a binary tree

Length of the longest path from the root node to a leaf node is the height of the binary tree. We find it in linear time using a recursive algorithm

Akshay Gopani

Akshay Gopani

Introduction to Q Learning and Reinforcement Learning

Read on to learn the basics of reinforcement learning and Q-Learning through an intuitive explanation, and a TensorFlow implementation!

Источник

Оцените статью