Docsity

Arrays in Java, Slides of Computer science

Toggle sidebar
bg1
AP Computer Science Arrays in Java 1
Arrays And ArrayLists
"Should array indices start at 0 or 1? My
compromise of 0.5 was rejected without, I
thought, proper consideration. "
- S. Kelly-Bootle
AP Computer Science Arrays in Java 2
Arrays in Java
Java has built in arrays as well as more complicated classes
to automate many array tasks (the ArrayList class)
arrays hold elements of the same type
– primitive data types or classes
– space for array must be dynamically allocated with new operator.
(Size is any integer expression. Due to dynamic allocation does not
have to be a constant.)
public void arrayExamples()
{ int[] intList = new int[10];
for(int i = 0; i < intList.length; i++)
{ assert 0 >= i && i < intList.length;
intList[i] = i * i * i;
}
intList[3] = intList[4] * intList[3];
}
AP Computer Science Arrays in Java 3
Array Details
all arrays must be dynamically allocated
arrays have a public, final field called length
– built in size field, no separate variable needed
– don't confuse length (capacity) with elements in
use
elements start with an index of zero, last index
is length - 1
trying to access a non existent element results
in an ArrayIndexOutOfBoundsException
(AIOBE)
AP Computer Science Arrays in Java 4
Array Initialization
Array variables are object variables
They hold the memory address of an array
object
The array must be dynamically allocated
All values in the array are initialized (0, 0.0,
char 0, false, or null)
Arrays of primitives and Strings may be
initialized with an initializer list:
int[] intList = {2, 3, 5, 7, 11, 13};
double[] dList = {12.12, 0.12, 45.3};
String[] sList = {"Olivia", "Kelly", "Isabelle"};
pf3
pf4
pf5

Partial preview of the text

Download Arrays in Java and more Slides Computer science in PDF only on Docsity!

AP Computer Science

Arrays in Java

1

Arrays And ArrayLists

"Should array indices start at 0 or 1? Mycompromise of 0.5 was rejected without, Ithought, proper consideration. "

- S. Kelly-Bootle

AP Computer Science

Arrays in Java

Arrays in Java

Java has built in arrays as well as more complicated classesto automate many array tasks (the ArrayList class) arrays hold elements of the same type– primitive data types or classes– space for array must be dynamically allocated with new operator.(Size is any

integer expression

. Due to dynamic allocation does not

have to be a constant.)

public void arrayExamples(){^

int[] intList = new int[10];for(int i = 0; i < intList.length; i++){^

assert 0 >= i && i < intList.length;intList[i] = i * i * i;

}intList[3] = intList[4] * intList[3];

AP Computer Science

Arrays in Java

3

Array Details

all arrays must be dynamically allocated arrays have a public, final field called

length

– built in size field, no separate variable needed– don't confuse length (capacity) with elements inuse elements start with an index of zero, last indexis length - 1 trying to access a non existent element resultsin an ArrayIndexOutOfBoundsException(AIOBE)

AP Computer Science

Arrays in Java

Array Initialization

Array variables are object variables They hold the memory address of an arrayobject The array must be dynamically allocated All values in the array are initialized (0, 0.0,char 0, false, or null) Arrays of primitives and Strings may beinitialized with an initializer list: int[]

intList

=^ {2,

3,^

5,^ 7,

double[]

dList

=^ {12.12,

String[]

sList

=^ {"Olivia",

"Kelly",

"Isabelle"};

AP Computer Science

Arrays in Java

5

Arrays of objects

A native array of objects is actually a nativearray of

object variables

– all object variables in Java are really what?– Pointers!^ public

void

objectArrayExamples()

{^

Rectangle[]

rectList

=^

new^

Rectangle[10];

//^ How

many

Rectangle

objects

exist?

rectList[5].setSize(5,10);//uh

oh! for(int

i^ =

i^ <

rectList.length;

i++)

{^

rectList[i]

=^ new

Rectangle();

} rectList[3].setSize(100,200); }

AP Computer Science

Arrays in Java

6

Array Utilities

In the

Arrays

class

binarySearch

,^ equals

,^ fill

, and

sort

methods for arrays of all primitive types(except boolean) and arrays of Objects– overloaded versions of these methods forvarious data types^ In the System class there is an

arraycopy

method to copy elements from a specifiedpart of one array to another– can be used for arrays of primitives or arrays ofobjects

AP Computer Science

Arrays in Java

7

The ArrayList Class

A class that is part of the Java StandardLibrary and a class that is part of the APsubset a kind of automated array not all methods are part of the ap subset

AP Computer Science

Arrays in Java

8

About Lists (in general)

A list is an ordered collection or a

sequence

ArrayList implements the List interface The user of this interface will have controlover where in the list each element isinserted. The user can access elements by theirinteger index (position in the list), and searchfor elements in the list. Items can be added, removed, and accessedfrom the list

AP Computer Science

Arrays in Java

13

How the methods work

remove–^ removes

the element at the specified index

– throws IndexOutOfBoundsException if index<0or index>=size– size will be decreased by 1– returns Object removed

AP Computer Science

Arrays in Java

Examples

ArrayList

club

new

ArrayList();

club.add(“Spanky”);club.add(“Darla”);club.add(“Buckwheat”);System.out.print(club); Displays:[Spanky, Darla, Buckwheat]

AP Computer Science

Arrays in Java

15

//using

club

from

previous

slide

club.set(1,

“Mikey”);

System.out.print(club); Displays:[Spanky, Mikey, Buckwheat]

AP Computer Science

Arrays in Java

//using

club

from

previous

slide

club.add(0,club.remove(club.size()-1));System.out.print(club); Displays:[Buckwheat, Spanky, Mikey]

AP Computer Science

Arrays in Java

17

//ArrayLists

only

contain

Objects!!

ArrayList

odds

new

ArrayList();

for(int

i=1;

i<10;

i+=2)

odds.add(new

Integer(i));

System.out.println(odds); Displays:[1, 3, 5, 7, 9]

AP Computer Science

Arrays in Java

//ArrayLists only contain Objects!!ArrayList odds = new ArrayList();for(int i=1; i<10; i+=2){ Integer x = new Integer(i);

odds.add(x);}

System.out.println(odds); Displays:[1, 3, 5, 7, 9]

AP Computer Science

Arrays in Java

19

Objects and Casting

//Casting when pulling out from ArrayListArrayList names = new ArrayList();names.add("Clint");names.add("John");names.add("Robert");names.add("Henry");Object obj = names.get(2); //okSystem.out.println( obj.toString() );String str1 = names.get(3); //syntax errorString str2 = (String)(names.get(4)); //okchar c =

((String)(names.get(0))).charAt(0);

//Gack!!

AP Computer Science

Arrays in Java

How the methods work

iterator– returns an Iterator object– Iterators allow all of the Objects in the list to beaccessed one by one, in order– methods for an Iterator object

  • hasNext• next• remove

AP Computer Science

Arrays in Java

25

Remove Example

public

void

removeAllLength(ArrayList

li,

int

len)

{^

//pre:

li

contains

only

String

objects

//post:

all

Strings

of^

length

=^ len

removed

//right

way String

temp; for(int

i^

=^ 0;

i^ <

li.size();

i++)

{^

temp

=^ (String)li.get(i); if(^

temp.length()

==^

len

{^

li.remove(i);i--; } } } What if the list contains ["hi", "ok", "the", "so", "do"] and len = 2?

AP Computer Science

Arrays in Java

Remove Example

public

void

removeAllLength(ArrayList

li,

int

len)

{^

//pre:

li^

contains

only

String

objects

//post:

all

Strings

of

length

=^ len

removed

//right

way

using

iterator

String

temp; iterator

it

=^ li.iterator();

while(

it.hasNext()

{^

temp

=^ (String)li.next(); if(^

temp.length()

len

it.remove();

} } What if the list contains ["hi", "ok", "the", "so", "do"] and len = 2?