Title: CS2851
1Arrays and Collections
- Intro to the Java Collections Framework
2Java Array Review
- Declaration of an array ltdatatypegt
ltvariablegt // approach 1 - ltdatatypegt ltvariablegt // approach 2
- Creation of the actual array ltvariablegt
new ltdatatypegtltsizegt
3The distinction between declaration and creation
- int scores // or int scores
- After Declaration of an array, a variable that
references an array is created somewhere in
memory - But since theres no actual array (yet), the
variable has a value of null.
Start of Memory
scores
null
End of Memory
4The distinction between declaration and creation
- int scores // or int scores
- scores new int12
- After Creation of the array, the memory for the
array elements is allocated and the variable is
assigned to reference the first element of the
array - All elements of the array are initialized (in
this case) to 0. -
scores
addr
0
0
0
0
0
0
0
0
0
0
0
0
5After assigning values to the array elements
- int scores // or int scores
- scores new int12
- for( int i0 iltscores.length i )
- scoresi i
-
The index of the first position in an array is 0.
6Another approach Simultaneous declaration
creation, and initialization of an array
8
7
4
5
6
5
8
9
10
5
8
10
7Declaring an array of objects
- Person people
- people new Person3
- The people array is actually an array of
references to Person objects - After Creation of the array, the memory for the
array elements is allocated and the variable is
assigned to reference the first element of the
array - All elements of the array are initialized (in
this case) to null. -
people
addr
null
null
null
8Creating an array of objects
- Person people
- people new Person3
- people0 new Person(A)
- When a Person object is created, the object is
placed somewhere in memory. The new operator
returns this address in memory. - After initializing an array element to reference
an instance of a Person object, the array element
is assigned to reference to the Person object
people
addr
addr
null
null
Person
9Another way of looking at it
Code
One Person object is created and the reference to
this object is placed in position 0.
State of Memory
10Simultaneous declaration creation, and
initialization of an object array
0
1
2
Person B
Person C
11Element Deletion
Delete Person B by setting the reference in
position 1 to null. What problem does this
introduce?
12Element Insertion (?)
What happens??
13Element Insertion problems
The old element is simply replaced. What happened
to B???
0
1
2
3
D
A
C
E