Што такое Autoboxing і распакаванне ў Java?

Autoboxing & unboxing

Autoboxing & распакаванне

Агляд: У гэтым артыкуле мы абмяркуем аб Autoboxing / распакаванне асаблівасцю Java. Autoboxing і распакаванне ў асноўным функцыя для пераўтварэння прымітыўных тыпаў дадзеных на аб'екты і наадварот. Увесь працэс ажыццяўляецца аўтаматычна з дапамогай Java часу працы асяроддзя. Але варта выконваць асцярожнасць пры рэалізацыі гэтай функцыі ў адваротным выпадку яна будзе мець уплыў на прадукцыйнасць прыкладанняў.

Увядзенне
Да версіі JDK 1.5, гэта было не так лёгка пераўтварыць прымітыўныя тыпы дадзеных e.g INT, голец, float, два разы на іх эквівалент аб'екта - Integer, характар, тарка, Двайны. JDK 5 прыйшоў з функцыяй аўтаматычнага пераўтварэння прымітыўных тыпаў дадзеных у іх эквівалент аб'екта. Гэтая функцыя называецца Autoboxing. На адваротным баку гэта вядома як распакаванне. i.e. працэс пераўтварэння аб'ектаў у адпаведныя прымітыўныя тыпы дадзеных называецца распакаванне. Прыклад кода для абодвух Autoboxing і распакаванне паказана, як пад -

Autoboxing

[код]

Цэлы лік Integer = 9;

[/код]

распакаванне

[код]

INT у = 0;

у = новы Integer(9);

[/код]

Калі Autoboxing і выкарыстоўваецца распакаванне?

Autoboxing ўжываецца Java-кампілятар ў наступных умовах -

  • Калі элементарнае значэнне перадаецца ў якасці параметру метаду, які чакае аб'ект адпаведнага класа-абалонкі.
  • Калі элементарнае значэнне прысвойваецца зменнай адпаведнага класа-абалонкі.

Разгледзім наступны прыклад -

Listing1: Прыклад кода, які паказвае Autoboxing

[код]

грамадскія INT sumEvenNumbers(спіс<цэлы лік> IntList ) { int sum = 0; для (цэлае я: IntList ) калі ( я % 2 == 0 ) sum = i; return sum;}

[/код]

да Jdk 1.5, Магчыма, прыведзены вышэй фрагмент кода прывяло б да памылкі кампіляцыі, так як рэшту аператар - '%' і унарный плюс - ' =' не можа быць ужыты на Цэлыя. Але так як JDK 1.5 гэты кавалак кода кампілюе і працуе без якіх-небудзь памылак, як ён пераўтворыць цэлы лік INT падчас выканання.

Распакаванне ўжываецца Java-кампілятар ў наступных умовах -

  • Калі аб'ект перадаецца ў якасці параметру метаду, які разлічвае адпаведнае элементарнае значэнне.
  • Калі аб'ект прысвойваецца зменнай адпаведнага тыпу прымітыву
  • Разгледзім наступны прыклад -

Listing2: Прыклад кода, які паказвае распакаванне

[код]

імпарт java.util.ArrayList;імпарт java.util.List; public class UnboxingCheck { дзяржаўнай статычнай сілы асноўных(Радок[] аргументы) { Integer in = new Integer(-8); // 1. Unboxing through method invocation int absVal = absoluteValue( in ); System.out.println( “абсалютная значэнне ” + in + ” = ” + absVal ); спіс<Двайны> doubleList = новы ArrayList<Двайны>(); // It is autoboxed through method invocation. doubleList.add(3.1416); // 2. Unboxing through assignment double phi = doubleList.get(0); System.out.println( “фі = ” + фіта ); } public static int absoluteValue( INT I ) { return (я < 0) ? -я : я; }}

[/код]

Autoboxing і распакаванне дазваляе распрацоўнікам пісаць код, які лёгка чытаць і разумець. У наступнай табліцы прадстаўлены прымітыўныя тыпы дадзеных і іх адпаведныя аб'екты-абалонкі -

прымітыўнага тыпу ўпаковачны Класс
лагічны лагічны
byte байт
голец характар
float тарка
дзесятковага цэлы лік
доўгі доўгі
кароткая кароткі

табліца - 1: Primitive data type and their equivalent wrapper classes With Comparison operators

Autoboxing and unboxing can be done with comparison operators. The following code snippet illustrates how it can be done –

Listing3: Sample code showing Autoboxing and unboxing using comparison operators

[код]

public class BoxedComparator {

дзяржаўнай статычнай сілы асноўных(Радок[] аргументы) {

Integer in = new Integer(25);

калі (in < 35)

System.out.println(“Value of int = ” + in);

}

}

[/код]
Autoboxing and unboxing with method overloading

Autoboxing or unboxing is done in case of method overloading. This happens based on the following rules –

  • Widening beats boxing – When there is a situation to choose between widening and boxing, пашырэнне прымае перавагу -

Listing4: Прыклад кода, які паказвае перагрузкі перавагу

[код]

грамадскага класа WideBoxed { грамадскага класа WideBoxed { static void methodWide(INT I) { System.out.println(“дзесятковага”); } static void methodWide( цэлае я ) { System.out.println(“цэлы лік”); } дзяржаўнай статычнай сілы асноўных(Радок[] аргументы) { short shVal = 25; methodWide(shVal); } }}

[/код]

Выхад гэтай праграмы - INT

  • Widening б'е зменнай даўжыні - Калі ўзнікае сітуацыя, каб зрабіць выбар паміж пашырэннем і спісаў параметраў, пашырэнне прымае перавагу -

Listing5: Прыклад кода, які паказвае перагрузкі перавагу

[код]

public class WideVarArgs {

static void methodWideVar(int i1, int i2) {

System.out.println(“int int”);

}

static void methodWideVar(цэлы лік… я) {

System.out.println(“Integers”);

} дзяржаўнай статычнай сілы асноўных( Радок[] аргументы) {

short shVal1 = 25;

short shVal2 = 35;

methodWideVar( shVal1, shVal2);

}

}

[/код]

  • Boxing beats Varargs – When there is a situation to choose between boxing and varargs, boxing takes the preference –

Listing6: Прыклад кода, які паказвае перагрузкі перавагу

[код]

public class BoxVarargs {

static void methodBoxVar(Integer in) {

System.out.println(“цэлы лік”);

}

static void methodBoxVar(цэлы лік… я) {

System.out.println(“Integers”);

}

дзяржаўнай статычнай сілы асноўных(Радок[] аргументы) {

int intVal1 = 25;

methodBoxVar(intVal1);

}

}

[/код]

Things to remember in order to use Autoboxing –

As we know that every good feature comes with some drawbacks, Autoboxing is not an exception in this regard. Some important bullets which a developer should keep in mind while using this feature are as under –

  • Comparing objects with equality operator – The equality operator – ‘==’ leads to confusion as it can be applied to both primitive data types and the object. When the operator is applied on objects, it actually compares the reference of the objects and not the values.

Listing7: Sample code showing comparison

[код]

public class Comparator {

дзяржаўнай статычнай сілы асноўных(Радок[] аргументы) {

Integer istInt = new Integer(1);

Integer secondInt = new Integer(1);

калі (istInt == secondInt) {

System.out.println(“both one are equal”);

} яшчэ {

System.out.println(“Both one are not equal”);

}

}

}

[/код]

  • Mixing object and primitive in equality and relational operator – If we compare a primitive data type with an object, then the unboxing occurs which may throw a NullPointerException if the object is null.
  • Cached Object – Since the valueOf()method is used to create boxed primitive objects, the used objects are cached. Since java caches integers from -128 to 128, these cached objects may behave differently.
  • Performance degradation – Autoboxing or unboxing degrades the performance of an application as it creates an unwanted object which leads the GC to run more frequently.

Disadvantage of Autoboxing

Though autoboxing has several advantages, it has the following disadvantage –

  • If autoboxing happens within a loop unnecessary objects gets created and it may slow down the performance of the application. Consider the following code –

Listing8: Sample code showing performance issue

[код]

грамадскія INT sumEvenNumbers(спіс<цэлы лік> IntList) { int sum = 0; для (цэлае я: IntList) калі ( я % 2 == 0 ) sum = i; return sum;}

[/код]

In this piece of code, [код] sum = i; [/код] will expand as [код] сума = сума + я; [/код]. Since the ‘ ’ operation cannot be done on Integer object, the JVM triggers the unboxing of sum Integer Object and then the result is autoboxed back.

  • да Jdk 1.5, data types int and Integer were distinct and in case of method overloading these two types were used without any hassle. Now with autoboxing and unboxing, this has become trickier. An example of this is the overloaded remove method in ArrayList. Class ArrayList has two remove methods – remove (index) and remove (object). In this case, method overloading will not happen and the respective method will be called with appropriate parameters.

Заключэнне

Autoboxing is the mechanism to covert a primitive data type into respective wrapper or Object. Compiler uses valueOf() method to convert primitive to Object and uses intValue(), doubleValue() etc to get primitive value from Object. In autoboxing, a boolean is converted to Boolean, byte to Byte, char to Character, float changes to Float, int goes to Integer, long goes to Long and short converts to Short, у той час як у распаковывания пераўтварэнне адбываецца ў зваротным кірунку.

Tagged on: , ,
============================================= ============================================== Buy best TechAlpine Books on Amazon
============================================== ---------------------------------------------------------------- electrician ct chestnutelectric
error

Enjoy this blog? Please spread the word :)

Follow by Email
LinkedIn
LinkedIn
Share