Simple Arrays in Java don't come with many features, so it is often better to use ArrayLists instead. ArrayList implements the List and Collection interfaces, which means that it can easily be swapped with another List class.
Jim is creating some simple software to track orders in his store. Identical orders will need to be stored separately. Most items will be added to the end of the list and he'll rarely need to insert or delete items.
Since Jim wants to allow duplicates, he'll need a List instead of a Set. Since there won't be many deletions or insertions, Jim used an ArrayList.
The following code will declare and create an empty ArrayList of Strings in Java 7:
ArrayList<String> orders = new ArrayList<>();
In Java 6, you need to specify the type of ArrayList in the initialization too:
ArrayList<String> orders = new ArrayList<String>();
An ArrayList constructor can also take in a Collection and create an ArrayList with the elements of that collection. For example, if you had a HashSet called hash, you could create an ArrayList with the following code:
ArrayList<String> list = new ArrayList<String>(hash);
Let's start by adding four Strings to the ArrayList. Each String will be added to the end of the List:
orders1.add("apple"); orders1.add("banana"); orders1.add("cantaloupe"); orders1.add("date");
Now let's print the ArrayList to see what it looks like. Printing an ArrayList calls the toString method of Collection, which returns a String with a comma-separated list of the items.
[apple, banana, cantaloupe, date]
Jim wants to let people save copies of their orders so that they can be re-used another time. If he creates another ArrayList and sets its value to the first, it will just create another variable that points to the same ArrayList Object. This means anything that happens to one ArrayList, will happen to the other one, since they're really the same:
ArrayList<String> orders2 = orders1; orders2.remove("cantaloupe"); //removes "cantaloupe" from orders2 which is same as orders1 System.out.println(orders1);
This will print:
[apple, banana, date]
To create a separate copy of the ArrayList, which can be edited without affecting the original
orders1 list, Jim uses the addAll method, which can add all the items from any Collection to an ArrayList:
ArrayList<String> changingOrders = new ArrayList<String>(); changingOrders.addAll(orders1); // [apple, banana, date] changingOrders.add("eggplant"); //adds "eggplant" to changingOrders, but not to orders1
Each List is now different and will print different results.
[apple, banana, date] [apple, banana, date, eggplant]
addAll can also be used to add elements to a list that already has elements.
ArrayList adding and removing
There are 3 basic ways to add single items to an ArrayList:
- add it normally, and it will be placed at the end of the List.
- add an integer parameter to specify at what index the item should be placed in the list. This will shift the elements on the right one over to make space.
Use set to replace an element at the specified index with the given element.
orders1.add("apple"); // [apple, banana, date, apple] orders1.add(2, "cantaloupe"); //[apple, banana, cantaloupe, date, apple] orders1.set(4, "eggplant");
The list will now look like:
[apple, banana, cantaloupe, date, eggplant]
There are 2 basic ways to remove single items from an ArrayList:
- Specify the item to be removed and remove the first occurrence of the item
- Specify the index to remove an item from.
In each case, the items on the right will be shifted one to the left to fill the gap:
orders1.remove("apple"); //[banana, cantaloupe, date, eggplant] orders1.remove(1);
The List now:
[banana, date, eggplant]
To remove multiple items at a time, you can use removeAll and pass in a collection of items that will all be removed from the List.
This will print a single-item list:
You can also remove all the items in a list with clear:
ArrayList getting elements and info
Let's add another banana:
The current List:
[banana, date, eggplant, banana]
There are also multiple way to find or get items in an ArrayList:
- indexOf will return the index of the of the first occurrence of a given element, and -1 if the element isn't found.
- lastIndexOf will return the last occurrence of an item.
get will return an item at a specific index.
int index = orders1.indexOf("banana"); // index = 0. index = orders1.indexOf("ketchup"); // index = -1. index = orders1.lastIndexOf("banana"); //index = 3. String fruit = orders1.get(0); // fruit = "banana".
You can also find out information about an ArrayList, such as if it contains an element or any elements, and its size.
- isEmpty returns true if list is empty, i.e. has no elements.
- contains returns true if list contains the specified element.
size returns the number of items in the list
boolean empty = orders1.isEmpty(); //empty = false. boolean have = orders1.contains("apple"); // have = false. int size = orders1.size(); //size = 4.
To convert ArrayList to array, first create an Array of the correct size and then pass it as parameter to toArray.
String orderArray = new String[size]; orders1.toArray(orderArray);
orderArray will now have the same elements and order as the ArrayList, but will be its own separate copy.