Java Reference
In-Depth Information
Forexample,youcanuse
new
tocreateaone-dimensionalarrayofobjectreferences,
asdemonstratedbythefollowingexample,whichcreatesaone-dimensionalarraythat
can store ten
Image
object references:
Image[] imArray = new Image[10];
Whenyoucreateaone-dimensionalarray,
new
zerosthebitsineacharrayelement's
storage location, which you interpret at the source code level as literal value
false
,
'\u0000'
,
0
,
0L
,
0.0
,
0.0F
,or
null
(dependingonelementtype).Intheprevious
example,eachof
imArray
'selementsisinitializedto
null
,whichrepresentsthe
null
reference
(a reference to no object).
Aftercreatinganarray,youneedtoassignobjectreferencestoitselements.Thefol-
lowing example demonstrates this task by creating
Image
objects and assigning their
references to
imArray
elements:
for (int i = 0; i < imArray.length; i++)
imArray[i] = new Image("image"+i+".png"); // image0.png,
image1.png, and so on
The
"image"+i+".png"
expressionusesthestringconcatenationoperator(
+
)to
combine
image
withthestringequivalentoftheintegervaluestoredinvariable
i
with
.png
.Theresultingstringispassedto
Image
's
Image(String filename)
con-
structor.
Caution
Use of the string concatenation operator in a loop context can result in a
lotofunnecessary
String
objectcreation,dependingonthelengthoftheloop.Iwill
You can also use
new
to create arrays of primitive type values (such as integers
or double precision floating-point numbers). For example, suppose you want to create
a two-dimensional three-row-by-two-column array of double precision floating-point
temperature values. The following example accomplishes this task:
double[][] temperatures = new double[3][2];
After creating a two-dimensional array, you will want to populate its elements with
suitable values. The following example initializes each
temperatures
element,
whichisaccessedas
temperatures[row][col]
,toarandomlygeneratedtemper-
for (int row = 0; row < temperatures.length; row++)
for (int col = 0; col < temperatures[row].length; col++)
temperatures[row][col] = Math.random()*100;