Arrays
a collection of like items; bounded;
fixed; can be anything including an array of objects; if an array of
object; each object in the array must be instantiated (with new
operator); the object references have null in them by default.
int[] numbers = new int[50];
(defines a single, one-dimension array of 50 cells or elements)
number[5] = 79; //puts 79
into 6th cell or element
int x = number[5]; //stores value in 6th cell into x
Frogs[] [] greenThings =
new [50][50];
(defines a double, two-dimension array of 50 X 50 cells or elements)
greenThings[0]
[1]= new Frogs(); //creates valid Frog object into
//row 0 and second column in that row
length is a
constant built into array which gives you the size of the array.
for example (from above): numbers.length would equal 50;
ArrayLists (implements List Interface)
a collection of objects; unbounded;
dynamic -- grows and shrinks as you add and remove items to and
from; use methods to manipulate items in the ArrayList.
declare and
instantiate an ArrayList
ArrayList<String> info = new ArrayList<String>();
//notice that we put the type of objects in <> next to the word
ArrayList
//this specifies that the ArrayList contains object of <> type
//Strings in the above example..
ArrayList Methods
(assuming ArrayList called info):
info.size() -> to get size ->info.size(); //returns integer;
info.add("nick"); //adds/appends string literal "nick" to end of
info list; returns true
info.add(i,"nick"); //inserts string literal "nick" to spot i (i is
an integer) in list; returns void
String record=info.get(i);
//returns back the element information at element i in the ArrayList
-- since this ArrayList is a list of Strings;
you must receive back a String.
String record = info.get(i);
to change information in
an item; for example to change the first item in the ArrayList which
sits at index 0 and currently has "nick" in it with "billy"; do:
Sting oldOne=info.set(0,"billy"); //returns back object (the string
in this case)
//currently in position 0 and replaces with "billy"
//first arg which is 0, is the item (index, element) to change
to remove an item from
ArrayList; for example to remove the first item in the ArrayList
which sits at index 0 and currently has "nick" in it ; do:
Sting oldOne=info.remove(0); //returns back object (the string in
this case)
//currently in position 0
//first arg which is 0, is the item (index, element) to remove
//ArrayList info is now one less item than prior to remove
call
|