-
What's happened
autoboxing
?Autoboxing is a mechanism for implicitly initializing objects of wrapper classes (Byte, Short, Character, Integer, Long, Float, Double) with the values of their corresponding original primitive types (respectively, , , , , , ,
byte
,short
)char
,int
withoutlong
explicitfloat
usedouble
of the class constructor.Autoboxing occurs when a primitive is directly assigned to a wrapper class (using the "
=
" operator), or when a primitive is passed into the parameters of a method (such as a "wrapper class"). Both variables of primitive types and compile-time constants (literals andfinal
-primitives) can be autopacked into “wrapper classes”. In this case, literals must be syntactically correct to initialize a variable of the original primitive type.Autoboxing of variables of primitive types requires an exact match of the type of the original primitive - the type of the “wrapper class”. For example, attempting to autobox a type variable
byte
intoShort
, without first making an explicit cast,byte->short
will cause a compilation error.Autoboxing of primitive type constants allows for wider matching boundaries. In this case, the compiler is able to perform implicit extension/narrowing of primitive types in advance. The transformation occurs in two stages:
-
implicit expansion (narrowing) of the original primitive type to the primitive type corresponding to the wrapper class (for conversion
int->Byte
, first the compiler implicitly narrowsint
tobyte
) -
autopacking of a primitive into the appropriate “wrapper class” (the compiler autopacks
byte->Byte
). however, in this case there are two additional restrictions: -
assignment of a primitive to a “wrapper” can only be done using the “
=
” operator (you cannot pass such a primitive to method parameters without explicit type casting) -
the type of the left operand must not be older than
Character
, the type of the right operand must not be older thanint
, (extension/constriction is allowedbyte <-> short
,byte <-> char
,short <-> char
and only narrowingbyte <- int
,short <- int
,char <- int
, all other options require explicit type casting)
An additional feature of integer "wrapper classes" created by autoboxing constants in the range -128 +127 is that they are cached by the JVM. Therefore, such wrappers with the same values will be references to one object.
-
-
Why is it used
autoboxing
?I will quote the lecture:
As you remember, Java has both types inherited from the class
Object
and primitive types. But, as it turned out, such a convenient thing as collections and generics can only work with types inherited fromObject
. -
Alternatives
autoboxing
?Не нашел ответа, но запостил на StackOverFlow.
Исходя из этой дискуссии, получается, что альтернатива
autoboxing
`у это использование примитивных типов, так How использовниеautoboxing
`a снижает производительность. Вывод: использоватьautoboxing
только там где это необходимо.Написана статья про
Autoboxing
: Autoboxing: Traps and Advantages -
Типы-обертки для примитивных типов
mutable
orimmutable
?Immutable
, так How примитивные an objectы тожеimmutable
. Whatбы работать How сMutable
типом есть классMutableInteger
, и.т.д. -
Как примитивные типы приводятся к непримитивным аналогам?
На этот и последующий вопросы хорошо отвечает вот эта статья: Автоупаковка и распаковка в Java
Это заключение из нее: автоупаковка является механизмом для скрытого преобразования примитивных типов данных в соответствующие классы-оболочки (an objectы). Компилятор использует метод
valueOf()
чтобы преобразовать примитивные типы в an objectы, а методыIntValue()
,doubleValue()
и т.д., чтобы получить примитивные типы из an object (то есть обратное преобразование). Автоупаковка преобразует логический типboolean
вBoolean
,byte
вByte
,char
вCharacter
,float
вFloat
,int
вInteger
,long
вLong
,short
вShort
. Распаковка происходит в обратном направлении. -
Как непримитивные типы приводятся к примитивным?
Выше ответил.
-
Как сравниваются примитивные и непримитивные типы?
В лекции это подробно рассматривается, но я нашел так скажем тоже самое, но другими словами.
В Java есть два способа сравнивать an objectы на equalsство,
==
и методequals()
.==
используется для примитивных типов. Для an objectов «==
» это исключительно сравнение ссылок. Для остальных случаев нужно использовать методequals()
. Кроме того методhashCode()
служит (в теории) для той же цели. Хорошим тоном считается, если вы переопределorequals()
иhashCode()
. После инициализации неких an objectов a и b должно выполняться правило:Если выражение
a.equals(b)
вернет true, тоa.hashCode()
должен быть equalsb.hashCode()
. -
Всегда ли создается новый an object при операции
autoboxing
?Это в лекциях есть:
Когда мы присваиваем переменной типа Integer meaning типа
int
, при этом вызывается методInteger.valueOf
: функцияvalueOf
не всегда создает новый an object типа Integer. Она кэширует значения от -128 до 127.Если передаваемое meaning выходит за эти пределы, то новый an object создается, а если нет, то нет.
Если мы пишем
new Integer()
, то гарантированно создается новый an object. Если мы вызываемInteger.valueOf()
, явно or приautoboxing
, то этот метод может вернуть для нас How новый an object, так и отдать an object из кэша, если переданное число лежит в диапазоне от -128 до 127. -
Как работает кэширование при операции
autoboxing
?Ответил в вопросе выше, на всякий случай создал вопрос на StackOverFlow, но там отвечают тоже самое
-
Для Howих типов и/or значений работает кэширование?
В восьмом вопросе. Если у кого – то есть соображения на тему трех последних вопросов, то напишите в комментариях.
DefNeo
Level 36
GO TO FULL VERSION