• Skip to main content
  • Skip to primary sidebar
  • Home
  • About
  • Subscribe BMA
  • Contact Us!

Be My Aficionado

Inspire Affection

You are here: Home / Programming / Simple Shopping Cart Project in JAVA using Collections

Simple Shopping Cart Project in JAVA using Collections4 min read

September 9, 2016 by Varun Shrivastava 10 Comments

If you have read my previous article which solely focuses on getting you started with the JAVA Collections framework then it’s time to dig a little deeper and create a Shopping Cart application to demonstrate the use of Collections in a real-world application.

I have chosen Shopping Cart application for this purpose because I found it perfect for implementing collections in this application.

Shopping Cart application will help you in modelling real-world entities into code.

Topics Covered

  • Project Structure
  • Classes Used
    • Product.java
    • Products.java
    • Cart.java
    • UI.java
    • Main.java
  • Conclusion

Project Structure

  1. Create a new Java Project with whatever name you like.
  2. Create the following package under your src folder,
    • collections.shoppingcart
  3. For simplicity, all of the code will reside inside this package.

Classes Used

  • Product.java
  • Products.java
  • Cart.java
  • UI.java
  • Main.java

For this example project, make sure all of the above-mentioned classes resides under the same package, i.e, collections.shoppingcart.

I will take each class one by one and explain the significance of it.

Product.java

Go through the code below,

This is a concrete class which contains Product properties and provides setters and getters for it. I have also override the Hash and Equals method.

  • equals()method is used to compare two objects based on their properties.
  • hashCode()is a unique hash/number attached to every object whenever the object is created.

So whenever two objects are compared. Their hash code and properties are compared. If both (hash code & properties value) are same then the object is considered equal otherwise not equal.

Therefore, it is very important to override hascode() and equals() method of an object.

Following is a very well explained answer that tells you the importance of overriding hashcode and equals for object comparison.

  • Why do I need to Override equals and hashCode method in Java?

Products.java

Go through the code below,

The role of this class in your Shopping Cart Application is to provide you with the store products.

In other words, this class is used to initialize your store as soon as the application is started. In real-world application, the items will be retrieved from user session or database. For simplicity, I’m using Products class to initialize objects.

As you can see, theinitStoreItems()method is used to add the products into a new ArrayList of type Product.

If you have read my previous article on Understanding Collections in JAVA then you will be familiar with the Generic Collection.

As we have provided the Product class inside the <> braces as new ArrayList(), this will tell the compiler that the list is of type Product and it can only contain an item which belongs to type Product.

Cool.

You are half way there.

Cart.java

This is a concrete class which act as a virtual cart to store the items temporarily.

It provides all the required operations a cart should have such as:

  • addToCart()
  • removeFromCart()
  • getProduct(), etc…

It also maintains a cartItems list with a type Product, similar to the products list in products class.

The sole purpose of cartItemslist is to store the purchased item in the cart or remove the item from the cart. It simply maintains the list of items which are added to the cart by the user.

UI.java

In the web application, you will have a nice looking HTML page with Javascript support. So the user will simply look for the product and click on the Add To Cart button.

In the console application (like this one), UI parts become a bit trickier. But, I’ve got a really cool way to make it easy.

Look:

In the console, a user can input only one input at a time. This is the key concept and could be used to make the UI easy.

People often take different input variables for different inputs. That could become a headache if there are tons of input to process.

That is why the simplest approach is to go with a single input variable and process it as soon as it gets populated.

In this application, I have used a single class variable to take user input. And based on the input value respective process will be executed.

Go through the code below and understand the concept.

This is the class where the main interaction between the user and application takes place.

It is the control point of the application.

Everything that you see in the console is a result of this page.

It takes the user input and calls the respective methods from the classes you made earlier to perform the required task.

Take a look at the code and come back if you have any question. I’m always here to answer.

Main.java

This is simply the starting point for the application.

It calls the constructor of UI() from the main method which takes care of bootstrapping the entire application.

Conclusion

Your Shopping Cart application is fully working at this point in time.

I hope the use of the collection is clear. If there is any doubt or problem then you may contact me directly by commenting below.

For simplicity, I have only used ArrayList, however, you may use any other data structure as per the need of the application. I suggest you follow the KISS principle every time you are given a project.

Let me know if you need to learn any other application from real world. I would be more than happy to do it.

Share this:

  • Click to share on Facebook (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • More
  • Click to print (Opens in new window)
  • Click to share on Tumblr (Opens in new window)
  • Click to share on Pocket (Opens in new window)
  • Click to share on Telegram (Opens in new window)
  • Click to share on WhatsApp (Opens in new window)
  • Click to share on Skype (Opens in new window)
  • Click to email this to a friend (Opens in new window)

Filed Under: Programming Tagged With: cart, collections, java, java programming, kiss, program, shopping cart

Reader Interactions

Comments

  1. Mohana Krishna says

    October 2, 2019 at 12:15 pm

    @Override
    public boolean equals(Object obj) {
    if (this == obj) {
    return true;
    }
    if (obj == null) {
    return false;
    }
    if (getClass() != obj.getClass()) {
    return false;
    }
    final Product other = (Product) obj;
    if (!Objects.equals(this.name, other.name)) {
    return false;
    }
    if (!Objects.equals(this.pid, other.pid)) {
    return false;
    }
    if (!Objects.equals(this.price, other.price)) {
    return false;
    }
    if (!Objects.equals(this.stock, other.stock)) {
    return false;
    }
    return true;
    }

    please kindly explain this

    Reply
  2. Kota Harsha Vardhan Reddy says

    March 6, 2019 at 1:06 am

    Hi bro, y dont u give the requirement at first , so that we try on our own and your code will help as a reference while developing it ?

    Reply
    • Varun Shrivastava says

      March 6, 2019 at 2:08 am

      Hey! Good Idea.
      Will implement it.

      As this post was intented to teach object oriented approach, I will add another article dedicated to problem statements along with their solutions.

      Reply
      • Kota Harsha Vardhan Reddy says

        March 6, 2019 at 8:43 am

        Please leave a link below when u do that ? Thanks. 🙂

        Reply
  3. Javier Pérez says

    March 5, 2019 at 2:02 am

    Is there no option to add what amount of product I add to the cart?

    Reply
    • Varun Shrivastava says

      March 5, 2019 at 8:16 am

      There is… Amount is a Product’s property. So, every product has a price.

      Reply
  4. Jason says

    December 29, 2018 at 7:39 pm

    Hi,Sir. First thank you for sharing this project. Im a student who currently on the learning process to create a prototype for E-Commerce Website. So i saw the code on UI.java is for the Console App, how about the code for Web App? What is the code for the function in the Add to Cart button ? Thanks for sir for the help!

    Reply
    • Varun Shrivastava says

      January 2, 2019 at 6:12 pm

      For the web, you will receive the HTTP request from the frontend with the product id (or whatever logic you want to implement).

      You will have to validate the request and add the product to the shopper’s cart.

      Maybe the following project will help you to build the prototype https://github.com/vslala/SpringMVC-Online-Shopping

      Reply
      • disqus_Hu1Amcbp6G says

        January 3, 2019 at 9:15 am

        vs_shrivastava already read

        Reply
        • Varun Shrivastava says

          January 3, 2019 at 10:30 am

          Was it helpful?

          If you want a prototype then my team can help you with that.

          Feel free to contact us at [email protected]

          Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Featured Posts

Time Complexity Comparison Sheet Of Elementary Sorting Algorithms

May 29, 2020 By Varun Shrivastava Leave a Comment

Freshers’ Journey to an IT Company – The Life of a Fresher

October 1, 2016 By Varun Shrivastava 2 Comments

Top 5 Indian movies every American must watch

November 1, 2016 By Varun Shrivastava Leave a Comment

The New Boy In Town (Pune)

July 8, 2016 By Varun Shrivastava 2 Comments

Does DISTANCE matter in Relationship

January 4, 2017 By Varun Shrivastava 6 Comments

Latest Posts

  • Study Abroad Destinations : Research and Review
  • Advent Of Code 2020 – Day 7 – Handy Haversacks
  • Advent Of Code 2020 – Day 6 – Custom Customs
  • Advent Of Code 2020 – Day 5 – Binary Boarding
  • Advent Of Code 2020 – Day 4 – Passport Processing

Categories

  • Blogging (101)
  • Cooking (11)
  • Fashion (7)
  • Finance & Money (12)
  • Programming (50)
  • Reviews (2)
  • Technology (22)
  • Travelling (4)
  • Tutorials (12)
  • Web Hosting (8)
  • Wordpress N SEO (19)

Follow us on facebook

Follow us on facebook

Grab the Deal Now!

Hostgator Starting @$3.95/mo

DigitalOcean Free Credits

Trending

Affordable Hosting amazon aoc-2020 bad luck believe in yourself best database earn money blogging education experience fashion finance Financial Freedom food friends goals google india indian cuisine indian education system java javascript life life changing love make money microservices motivation oops poor education system principles of microservices problem-solving programmer programming reality search engines seo SSD Hosting success technology tips top 5 web web developer wordpress

Copyright © 2021 · BeMyAficionado by Varun Shrivastava · WordPress

loading Cancel
Post was not sent - check your email addresses!
Email check failed, please try again
Sorry, your blog cannot share posts by email.