COMP 250 Lecture 4
Array lists
- Sept. 15, 2017
1
COMP 250 Lecture 4 Array lists Sept. 15, 2017 1 Arrays in Java - - PowerPoint PPT Presentation
COMP 250 Lecture 4 Array lists Sept. 15, 2017 1 Arrays in Java int[ ] myInts = new int[15]; myInts[3] = -732; Array whose elements have a primitive type 2 myInts int[ ] myInts = new int[15]; myInts[3] = -732; 0 0 1 0 2 0
1
2
1 2 3 :
14
:
myInts
The symbol here corresponds to some arguments that specify a shape.
4
shapes
1 : 293 : 427
1 2 3 :
14
: null null null null null null int[ ] myInts = new int[15]; myInts[3] = -732; Shape[ ] shapes = new Shape[428]; shapes[293] = new Shape( ); myInts
5
shapes
1 : 298 : 427
1 2 3 :
14
: null null null null null null myInts
In the C programming language, you have access to that value and can manipulate it. In Java, you have access to it but you can’t use it.
6
7
8
9
10
11
12
null null null
13
null null null
14
null null null
15
null null null
null null null
16
null null null
17
null null null
null null
1 2 size – 1
18 j u m p y j u m p y y j u e m p y j u m p p y j u m m p y
19
1 2 size – 1
j u m p y j u m p y y j u e m p y j u m p p y j u m m p y
20
if (a.size == a.length){ // is array full? make new bigger array b // e.g. b.length = 2*a.length for ( int i=0; i < size; i++) b[i] = a[i] // copy elements to b a = b }
21
22
23
Suppose we initialize an array list with an empty array of length 1. We then add an element.
arraylist of size 1 (length 1) arraylist of size 0 (length 1) add first element
What do we do to add a second element?
Suppose each time we add to a full array list, we double the length of the array.
add second element arraylist of size 1 (length 2) arraylist of size 2 (length 2) arraylist of size 1 (length 1)
.
add third element arraylist of size 2 (length 4) arraylist of size 2 (length 2) arraylist of size 3 (length 4)
.
add fourth element arraylist of size 3 (length 4) arraylist of size 4 (length 4)
.
add fifth element arraylist of size 4 (length 4) arraylist of size 4 (length 8) arraylist of size 5 (length 8)
.
add four elements add two elements add one element Double length and copy one element add one element Double length and copy two elements Double length and copy four elements
29
30
31
32
33
1 2 3 4 5
j u m p y j u m p y y j u e m p y j u m p p y j u m m p y
size = 6 size = 5
if ( (i >= 0) and (i < size) ){ tmp = a[i] // put aside and later return it for ( k = i; k < size-1; k++){ a[ k ] = a[ k + 1 ] // shift (copy) } size = size – 1 a[ size ] = null // clean return tmp }
34
35