java - Why Primitive Data types are fixed with their memory? -
my question:
why primitive data-types fixed in size?
how can collections grow in size dynamically?
suppose, primitive data-types contain feature or ability grow in size dynamically. reduce data-types 8 4 "integer" group of integer, float, short, long , float group of float, double. why isn't structure way?
any answer full. in advance.
hardware primitives have defined size, otherwise you'd have difficulties memory layout, converting bytes primitives , vice versa, etc. software primitives (built-in datatypes provided language) might not need fixed size make memory operations , data transfer more complex operations.
as example, if read integer file, how many bytes read? 1,2,4,8?
in memory you'd have similar problem: if object consist of 2 short integers, i.e. 2x2 bytes, you'd need move second integer if first needed grow or move entire object. performance penalty wouldn't compensated comfort of having 1 integer type.
collections on other hand, can grow since either reference different parts of heap or copy content larger portion of heap if more space needed.
take arraylist
example. internally uses array located in contiguous block of memory (otherwise accessing memory justing using address of array , index of element wouldn't work) , if array needs grow, bigger array created , original array copied new one.
linkedlist
on other hand distributed on heap, since each entry contains reference previous , next entry element. makes growing list easier accessing element require search elements until 1 you're interested found.
another example:
take array of int
values: 1,2,3,4,5,6
an array list (note jdk doesn't provide primitive lists there other libraries do) store them follows (hex values, byte order irrelevant example):
//those hex bytes |--- 1 ---| |--- 2 ---| |--- 3 ---| |--- 4 ---| |--- 5 ---| |--- 6 ---| 00 00 00 01 00 00 00 02 00 00 00 03 00 00 00 04 00 00 00 05 00 00 00 06
now if want access element 4 (index 3) need know memory address of first element , add index * 4
bytes position of 4th element. read next 4 bytes , have element value. (4 bytes because int
defined 32-bit i.e. 4 bytes).
without information you'd have take more action 4th element.
now consider linked list
element 0 <-> element 1 <-> element 2 <-> element 3 <-> element 4 <-> element 5 | | | | | | v v v v v v value 1 value 2 value 3 value 4 value 5 value 6
in memory elements might layed out this:
element 5, other stuff, element 3, element 4, other stuff, element 0, element 2, element 1
as can see, elements can anywhere in memory , can't access 4th element using memory address, index , size of element. instead, you'd have start @ element 0 locate element 1 2 etc. until have found element you're looking for.
Comments
Post a Comment