We've got 6 methods of the ArrayList class:
- myArrayList.size() returns the number of elements in the arraylist
- myArrayList.add(e) adds an element e to the end of the arraylist
- myArrayList.add(int loc, e) adds an element e to the arraylist at position loc and will move all following elements down one position
- myArrayList.get(int loc) returns the element at position loc
- myArrayList.set(int loc, e) replaces the element at position loc with a new element e
- myArrayList.remove(loc) removes the element at position loc
To create an ArrayList:
ArrayList<Integer> myIntegers = new ArrayList<Integer>();
ArrayList<Double> myDoubles = new ArrayList<Double>();
ArrayList<String> words = new ArrayList<Double>();
ArrayList<Tree> myTrees = new ArrayList<Tree>();
Specify what kind of ArrayList by using < >. Inside the triangle brackets, write what type of objects are in the ArrayList. Note, for int and double variables, you must use Integer or Double objects, since the elements of an ArrayList must be objects.
As with arrays, for loops are used with arraylists a lot to cycle through each of the elements.
No comments:
Post a Comment