Build a Shopping List Application with ArrayList in Java

ArrayList

What’s an ArrayList? Oracle documentation defines an ArrayList as a resizable array that implements List interface. ArrayList comes with a ton of methods that allow manipulation of the array. Some of the methods applicable in ArrayLize include, size, add, get, set, isEmpty and more. I will show how some of the methods work with using code.

When defining an ArrayList, it is important to specify the type because ArrayList holds objects. Above,we have specified the type as String. As such, the ArrayList defined will only be able to hold elements of type String.

Adding Items to ArrayList

ArrayList provides add method that can be used to add items to ArrayList. The method can be called using ArrayList variable defined earlier. In our case, we have created a method and passed an item that will be added to ArrayList using add method. See the following screenshot:

:
Print items in an ArrayList

I mentioned earlier that ArrayList provides several methods to manipulate data stored in ArrayList. Accessing items in an ArrayList can be done easily using “get” method. We have used a for-loop to circle through all the items in an ArrayList to retrieve and display them. Here is a code.

Modify/edit item in a List

We can also change an item already in a list using a method set that comes with ArrayList. However, a set method accept the item index position only and not the name (String) of an item. To achieve what we want, we overload two methods, one method is used by an external program that only accept the names, current item to be modified and new item and the other method that is used internally (a private method) - the method takes the index of an element and a new name. We also have a search method that searches the item and returns its position. Here are the codes:

Removing item from shopping list

What if we decide that some items or one item is unnecessary in our shopping list? The following methods will work perfectly in removing an item from the list:

Search for an Item

What if we have a long shopping list and we are not sure if a specific item has been added? We should have a function that checks if an item we intend to add and not sure if it’s already in the list. Here are the codes that work together to retrieve an searched item.

:

How the Shopping List App works?

Here is a preview of how the code works, the rest of the code is available here:Source Code.You can download and run it on your machine. I have also added a short video clip that shows how the application works, please check. Here is a screenshot of the output.

Here is a short clip that shows how the application works

Comments

Popular posts from this blog

Hangman Game With Python

File handling with C++ Programming