Lecture 22, CS 302-7 and 8, March 12
i. Don’t need to worry about initial size!
ii. It can grow
1. consider example above
iii. It can shrink
1. Why is this important? Well, when you declare an array, it holds that space in memory, so you can’t use it for anything else. So, if it’s possible that it might hold 1,000,000 things, you need to declare it that size. ArrayLists can shrink as appropriate.
iv. Finally – it’s easier! Fewer things to worry about
1. aka ArrayIndexOutOfBounds exceptions
i. Import ArrayList package
1. import java.util.ArrayList;
ii. Declare
1. ArrayList<String> words;
iii. Initialize
1. words =new ArrayList<String>();
iv. General form:
1. ArrayList<Type Parameter> name = new ArrayList<Type Parameter>();
v. What is the type parameter?
1. Tells the array list what kind of object to hold
vi. ***Note – you cannot pass primitives as Type Parameters
vii. If you want an arraylist of primitive types, instead pass wrapper classes
1.
Integer
2.
Double
3.
Character
viii. Note - you can still fill them with normal ints etc in the above case: al.add(1)
ix. What do we call a class that can take a type parameter like this?
1. Generic class – because it’s general
i. words=new ArrayList<String>();
ii. Note the () – this calls the class ‘constructor’. We’ll explain this soon. Kind of like rand=new Random();
iii. If you don’t initialize first - error
i. words.add(“Rob”); words.add(“Bill”); words.add(“Mitch”);
ii. Generally, name.add(element);
iii. Note – this adds to the end of the array list
i. words.size();
i. Say I wanted to get my name from the above ArrayList
1. words.get(1);
ii. Note – indexing starts at 0, just like arrays and string characters etc
iii. generally: name.get(index);
iv. Possible error – words.get(words.size())
i. Can use regular for loop or enhanced for loop
i. words.set(0, “Robert”);
ii. Generally:
1. name.set(index,new value);
iii. Note – this is just for overwriting existing values, not for adding new ones
i. words.add(1, “kevin”);
ii. generally-
1. name.add(index,new value);
iii. This inserts the new value at the given index, and ‘pushes everything back’ one spot.
iv. Thus, increases size of arraylist by 1
i. words.remove(1);
ii. Decrease size by 1, move all elements down
iii. Generally –
1. name.remove(index);