Learn More

Example ArrayList code

// This is coming from the Java Collection Frameworkimportjava.util.List;importjava.util.ArrayList;// This is using Generic syntax, we'll get to it...List<String>friends=newArrayList<>();friends.add("Ben");// adds "Ben" to the friends listfriends.size();// returns 1friends.contains("Ben");// returns truefriends.remove("Ben");friends.size()// returns 0

0:00

[MUSIC]

0:04

[SOUND] Now that we've
seen the power of arrays,

0:06

it's time to look at some
of their limitations.

0:08

Now, we've been dealing with arrays
where we either know all of the items at

0:12

declaration time or at least we know
how many there will be eventually.

0:17

In reality,
that's not always the case, is it?

0:20

I'm sure you can imagine programs where
we're taking input from a user, and

0:23

they want to either add or
remove elements from the array.

0:26

Now, if you recall when we first
started talking about this

0:29

fancy new data structure, we talked
about how it's length is immutable.

0:33

Now remember,
that means it can't be changed.

0:36

And the reason for this immutability
was because the declaration required

0:40

all of the elements to be one
after the other, contiguous.

0:45

So that brings up quite a big gotcha.

0:48

In order to add an element,

0:49

you would in fact have to change
the length of the array, and you can't.