Что такое классы обертки в java
Перейти к содержимому

Что такое классы обертки в java

  • автор:

Обёртки, распаковка и запаковка

Обёртки, распаковка и запаковка - 1

Привет! Ты уже неплохо знаком с примитивными типами, и немало с ними поработал. У примитивов в программировании, и в Java в частности, есть множество преимуществ: они занимают мало памяти, за счет чего повышается эффективность работы программы, и четко разделены по диапазонам значений. Однако в процессе изучения Java мы уже не раз, словно мантру, повторяли — “в Java все является объектом”. А ведь примитивы — прямое опровержение этих слов. Объектами они не являются. Получается, принцип “все является объектом” является ложным? На самом деле нет. В Java у каждого примитивного типа есть свой брат-близнец — класс-обертка ( Wrapper ). Что такое обертка? Обертка — это специальный класс, который хранит внутри себя значение примитива. Но поскольку это именно класс, он может создавать свои экземпляры. Они будут хранить внутри нужные значения примитивов, при этом будут являться настоящими объектами. Названия классов-оберток очень похожи на названия соответствующих примитивов, или полностью с ними совпадают. Поэтому запомнить их будет очень легко.

Классы оболочки в Java

Раньше Вы знакомились с примитивными типами данных (такими, как int, short, boolean и т.д.):

Variables Java_Vertex Academy

Тем не менее, Вы знаете, что Java — объектно-ориентированный язык программирования . Это значит, что в ней «все, что можно, представлено в виде объектов».

Поэтому, у примитивных типов есть объекты-аналоги — так называемые «классы оболочки» , или «wrapper» (с англ. «обертка, упаковка»):

wrap_1

Класс называется «оболочкой» потому, что он, по сути, копирует то, что уже существует, но добавляет новые возможности для работы с привычными типами .

О названиях

Имена классов нетрудно запомнить — они повторяют имена примитивных типов данных:

wrap_2

Обратите внимание — все классы оболочки пишутся с большой буквы:

wrap_3

Зачем так усложнять

Но зачем они нужны? Если есть обычный int, short, . , зачем нам Short и Integer ? Или, может, оставить только классы оболочки, и не пользоваться примитивами, раз у них функций больше ?

i-in3cvejg-evan-dennis

Примитивы и их аналоги, классы оболочки , существуют параллельно, потому что у каждого есть преимущества.

Например, обычный int занимает меньше места, и если нет необходимости проводить над ним особые операции, Ваш компьютер будет работать быстрее.

В свою очередь, с помощью класса-оболочки Integer можно выполнять специальные операции — например, перевести текст в число (с помощью метода .parseInt() для Integer-а ). Если попробовать сделать это с помощью кода самому придется изрядно повозиться.

Integer и int можно сравнить с компьютером и записной книжкой:

stocksnap_2ci87djpdzkopiya-stocksnap_0axtvi7jb2

Компьютер, безусловно, может больше, чем блокнот — но Вы не будете целый день носить с собой три килограмма для того, чтобы сделать несколько заметок?

Кроме того, есть ситуации, когда нельзя использовать объекты, или наоборот, когда можно использовать только объекты.

Метод .parseInt()

Иногда в объекте типа String содержится число, и Вам нужно с ним работать дальше — умножать, делить, в степень возводить. Но нельзя! Строка же. Что делать?

Wrapper classes in Java

Alok Gupta

The wrapper class in Java provides the mechanism to convert primitive into object and object into primitive.

Since J2SE 5.0, autoboxing and unboxing feature convert primitives into objects and objects into primitives automatically. The automatic conversion of primitive into an object is known as autoboxing and vice-versa unboxing.

Use of Wrapper classes in Java

Java is an object-oriented programming language, so we need to deal with objects many times like in Collections, Serialization, Synchronization, etc. Let us see the different scenarios, where we need to use the wrapper classes.

  • Change the value in Method: Java supports only call by value. So, if we pass a primitive value, it will not change the original value. But, if we convert the primitive value in an object, it will change the original value.
  • Serialization: We need to convert the objects into streams to perform the serialization. If we have a primitive value, we can convert it in objects through the wrapper classes.
  • Synchronization: Java synchronization works with objects in Multithreading.
  • java.util package: The java.util package provides the utility classes to deal with objects.
  • Collection Framework: Java collection framework works with objects only. All classes of the collection framework (ArrayList, LinkedList, Vector, HashSet, LinkedHashSet, TreeSet, PriorityQueue, ArrayDeque, etc.) deal with objects only.

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

Primitive TypeWrapper classbooleanBooleancharCharacterbyteByteshortShortintIntegerlongLongfloatFloatdoubleDouble

Autoboxing

The automatic conversion of primitive data type into its corresponding wrapper class is known as autoboxing, for example, byte to Byte, char to Character, int to Integer, long to Long, float to Float, boolean to Boolean, double to Double, and short to Short.

Since Java 5, we do not need to use the valueOf() method of wrapper classes to convert the primitive into objects.

Wrapper class Example: Primitive to Wrapper

  1. //Java program to convert primitive into objects
  2. //Autoboxing example of int to Integer
  3. publicclass WrapperExample1 <
  4. publicstaticvoid main(String args[]) <
  5. //Converting int into Integer
  6. int a=20;
  7. Integer i=Integer.valueOf(a);//converting int into Integer explicitly
  8. Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internally
  9. System.out.println(a+” “+i+” “+j);

Unboxing

The automatic conversion of wrapper type into its corresponding primitive type is known as unboxing. It is the reverse process of autoboxing. Since Java 5, we do not need to use the intValue() method of wrapper classes to convert the wrapper type into primitives.

Wrapper class Example: Wrapper to Primitive

  1. //Java program to convert object into primitives
  2. //Unboxing example of Integer to int
  3. publicclass WrapperExample2 <
  4. publicstaticvoid main(String args[]) <
  5. //Converting Integer to int
  6. Integer a=new Integer(3);
  7. int i=a.intValue();//converting Integer to int explicitly
  8. int j=a;//unboxing, now compiler will write a.intValue() internally
  9. System.out.println(a+” “+i+” “+j);
  10. >>

Java Wrapper classes Example

  1. //Java Program to convert all primitives into its corresponding
  2. //wrapper objects and vice-versa
  3. publicclass WrapperExample3 <
  4. publicstaticvoid main(String args[]) <
  5. byte b=10;
  6. short s=20;
  7. int i=30;
  8. long l=40;
  9. float f=50.0F;
  10. double d=60.0D;
  11. char c=’a’;
  12. boolean b2=true;
  13. //Autoboxing: Converting primitives into objects
  14. Byte byteobj=b;
  15. Short shortobj=s;
  16. Integer intobj=i;
  17. Long longobj=l;
  18. Float floatobj=f;
  19. Double doubleobj=d;
  20. Character charobj=c;
  21. Boolean boolobj=b2;
  22. //Printing objects
  23. System.out.println(“ — -Printing object values — -”);
  24. System.out.println(“Byte object: “+byteobj);
  25. System.out.println(“Short object: “+shortobj);
  26. System.out.println(“Integer object: “+intobj);
  27. System.out.println(“Long object: “+longobj);
  28. System.out.println(“Float object: “+floatobj);
  29. System.out.println(“Double object: “+doubleobj);
  30. System.out.println(“Character object: “+charobj);
  31. System.out.println(“Boolean object: “+boolobj);
  32. //Unboxing: Converting Objects to Primitives
  33. byte bytevalue=byteobj;
  34. short shortvalue=shortobj;
  35. int intvalue=intobj;
  36. long longvalue=longobj;
  37. float floatvalue=floatobj;
  38. double doublevalue=doubleobj;
  39. char charvalue=charobj;
  40. boolean boolvalue=boolobj;
  41. //Printing primitives
  42. System.out.println(“ — -Printing primitive values — -”);
  43. System.out.println(“byte value: “+bytevalue);
  44. System.out.println(“short value: “+shortvalue);
  45. System.out.println(“int value: “+intvalue);
  46. System.out.println(“long value: “+longvalue);
  47. System.out.println(“float value: “+floatvalue);
  48. System.out.println(“double value: “+doublevalue);
  49. System.out.println(“char value: “+charvalue);
  50. System.out.println(“boolean value: “+boolvalue);
  51. >>

Custom Wrapper class in Java

Java Wrapper classes wrap the primitive data types, that is why it is known as wrapper classes. We can also create a class which wraps a primitive data type. So, we can create a custom wrapper class 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.

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.

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.

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.

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.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *