I keep getting this error:

" Exception in thread "main" java.lang.ClassCastException: java.util.Collections$EmptySet cannot be cast to java.util.List
at JayJuan.InventoryManager.getProductList(InventoryManager.java:15)
at JayJuan.InventoryManager.addProduct(InventoryManager.java:48)
at JayJuan.InventoryApp.main(InventoryApp.java:35)
C:\Users\JonesJ58\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1 "

Based off this error and the code I provided please help me figure out how to get this program to run correctly. I am supposed to be using the InventoryManager and Product classes for methods and the InventoryApp class is the main class. InventoryApp class is supposed to be a simple application which uses a menu, a Scanner object, and an InventoryManager object to let users view, add, update, and remove product data. Please help me resolve this issue.

InventoryApp.java class

import java.util.Scanner;


public class InventoryApp
{
   public static void main(String[] args)
   {

       int option,quit;
       Scanner sc = new Scanner(System.in);
       while(true)
       {
           System.out.println("1.View 2. Add 3. Update 4. Remove and 5. Quit Product Menu:");
           System.out.println("Enter your Selection from the Above Menu Options:");
           option = sc.nextInt();
           switch (option)
           {
               case 1:
                   System.out.println("View the Product");
           {
               String upc = null;
               InventoryManager.getProduct(upc);
           }
                   break;
               case 2:
                   System.out.println("Add the Product");
           {
               Product p = null;
               InventoryManager.addProduct(p);
           }
                   break;
               case 3:
                   System.out.println("Update the Product");
           {
               Product p = null;
               InventoryManager.updateProduct(p);
           }
                   break;
               case 4:
                   System.out.println("Remove the Product");
           {
               String upc = null;
               InventoryManager.removeProduct(upc);
           }
                   break;
               case 5:
                   System.out.println("Exit from the Menu");                  
                   System.exit(0);                  
           }
       }

   }
}

InventoryManager.java class

import edu.lcc.citp.utility.CollectionFileStorageUtility;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


public class InventoryManager {


   public static List<Product> getProductList() {
       List<Product> products=null;
       try {
           products=(List<Product>) CollectionFileStorageUtility.load(Product.class);
       } catch (ClassNotFoundException e) {
           e.printStackTrace();
       } catch (IOException e) {
           e.printStackTrace();
       }
       return products;

   }

    /**
     *
     * @param upc
     * @return
     */
    public static Product getProduct(String upc)
   {
       List<Product> products = getProductList();
       for (Product pro : products) {
           if (pro.getUpc().equals(upc)) {
               return pro;
           }
       }
       return null;

   }

    /**
     *
     * @param p
     */
    public static void addProduct(Product p)
   {
       List<Product> products = getProductList();
       if(products!=null)
       {
           for (Product pro : products)
           {
               if (pro.getUpc().equals(p.getUpc()))
               {
                   System.out.println("A product with given upc alredy exist,cannot duplicate upc");
                   return;
               }
           }
       }
       else
       {
           products=new ArrayList<Product>();
       }
       products.add(p);
       try
       {
           CollectionFileStorageUtility.save(products, Product.class);
       }
       catch (IOException e)
       {
           e.printStackTrace();
       }
   }

    /**
     *
     * @param p
     */
    public static void updateProduct(Product p)
   {
       List<Product> products = getProductList();
       if(products==null)
       {
           return;
       }
       else
       {
           for (Product pro : products)
           {
               if (pro.getUpc().equals(p.getUpc()))
               {
                   if (!p.getLongDetails().isEmpty())
                   {
                       pro.setLongDetails(p.getLongDetails());
                   }
                   if (p.getPrice()!=null)
                   {
                       pro.setPrice(p.getPrice());
                   }
                   if (!p.getShortDetails().isEmpty())
                   {
                       pro.setShortDetails(p.getShortDetails());
                   }
                   if (pro.getStock()!=0)
                   {
                       pro.setStock(p.getStock());
                   }
                   return;
               }
           }
           System.out.println("A product with given upc does not exist");
       }

   }

   public static void removeProduct(String upc)
   {
       List<Product> products = getProductList();
       if(products==null)
       {
           return;
       }
       else
       {
           for (Product pro : products)
           {
               if (pro.getUpc().equals(upc))
               {
                   products.remove(pro);
                   return;
               }
           }
           System.out.println("A product with given upc does not exist");
       }

   }
}

Product.java class

import java.io.Serializable;
import java.math.BigDecimal;


public class Product implements Comparable<Product>,Serializable {

   private String upc;
   private String shortDetails;
   private String longDetails;private BigDecimal price;
   private int stock;

   public String getUpc() {
       return upc;
   }
   public void setUpc(String upc) {
       this.upc = upc;
   }
   public String getShortDetails() {
       return shortDetails;
   }
   public void setShortDetails(String shortDetails) {
       this.shortDetails = shortDetails;
   }
   public String getLongDetails() {
       return longDetails;
   }
   public void setLongDetails(String longDetails) {
       this.longDetails = longDetails;
   }
   public BigDecimal getPrice() {
       return price;
   }
   public void setPrice(BigDecimal price) {
       this.price = price;
   }
   public int getStock() {
       return stock;
   }
   public void setStock(int stock) {
       this.stock = stock;
   }


   public int compareTo(Product p) {
       if(this.getUpc().equals(p.getUpc()))
       {
           return 1;
       }
       return 0;
   }


}

CollectionFileStorageUtility.java class

package edu.lcc.citp.utility;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collection;
import java.util.Collections;

public class CollectionFileStorageUtility {

    private static final String FILE_DIR_NAME = ".citp290files";
    private static final Path FILE_DIR = Paths.get(System.getProperty("user.home")).resolve(FILE_DIR_NAME);


    public static <E extends Serializable> void save(Collection<E> collection, Class<E> clazz)
            throws IOException {

        final Path file = FILE_DIR.resolve(clazz.getName() + ".dat");
        if (!Files.exists(FILE_DIR)) {
            Files.createDirectory(FILE_DIR);
        }
        try (ObjectOutputStream oos = new ObjectOutputStream(Files.newOutputStream(file))) {
            oos.writeObject(collection);
        }

    }


    public static <E extends Serializable> Collection<E> load(Class<E> clazz)
            throws IOException, ClassNotFoundException {

        final Path file = FILE_DIR.resolve(clazz.getName() + ".dat");
        if (Files.exists(file)) {
            try (ObjectInputStream ois = new ObjectInputStream(Files.newInputStream(file))) {
                return (Collection<E>) ois.readObject();
            }
        } else {
            return Collections.emptySet();
        }
    }
}

It looks like the line causingthe error is line 71 above
products=(List<Product>) CollectionFileStorageUtility.load(Product.class);

I don't have any info on CollectionFileStorageUtility, but it seems to return a Collection. In this particular case the Collection is empty, but that's not a problem.

Java is objecting you trying to cast a Collection into a List. You don't know what kind of Collection is being returned, but whatever it is it's not a List.

Why declare products as a List? You get the data from a method that just returns a Collection, so why not declare it as a Collection as well? (and similarly in the other places where you declare a List)

List is a subclass of Collection so that is not a valid cast

the CollectionFileStorageUtility code is in the code above and is supposed to be added to the project we are working on. The full set of instructions are here:

For the Product class...

All "get" and "set" methods should be standard field accessors and mutators. You can use NetBeans to generate these for you!

The "compareTo" method should sort by the upc field. This means that it should return the result of comparing the current Product's upc ("this") with the parameter Product's upc ("p").

For the InventoryManager class...

"getProductList" should...
Use the CollectionStorageFileUtility's "load" method to load the Product class collection...

Add the collection to a new ArrayList object...

Return the new ArrayList.

"getProduct" should...

Call "getProductList" to get the list of Products...

Find a product with the matching UPC...

Return the matching product, or null if no such product exists.

"addProduct" should...

Call "getProductList" to get the list of Products...

Check to see if a product with the same UPC already exists...

If a product with the same UPC already exists then print an error message and return...

Otherwise, add the new product to the list...

Use the CollectionStorageFileUtility's "save" method to save the updated list.

"updateProduct" should...

Call "getProductList" to get the list of Products...

Check to see if a product with the same UPC exists...

If a product with the same UPC does not exist then print an error message and return...

Otherwise, for each non-null field in the parameter product other than the UPC, update that field for the product in the list...

Use the CollectionStorageFileUtility's "save" method to save the updated list.
"removeProduct" should...

Call "getProductList" to get the list of Products...

Check to see if a product with the same UPC exists...

If a product with the same UPC does not exist then print an error message and return...
Otherwise, remove that matching product from the list...

Use the CollectionStorageFileUtility's "save" method to save the updated list.

In your main method (inside InventoryApp.java) create a simple application which uses a menu (similar to the Module 1 Milestone), a Scanner object, and an InventoryManager object to let users view, add, update, and remove product data. Be sure to use a loop so that the user can perform as many menu choices as they like before they choose to quit.

I tried to stick to these as best I could, do you know what I'm missing?

OK, I didn't read all the rest of the code after I saw the problem. Anyway...

"getProductList" should...
Use the CollectionStorageFileUtility's "load" method to load the Product class collection...
Add the collection to a new ArrayList object

You need to follow the instructions you were given. Casting to List is not the same as adding to an new ArrayList.

Also, if you remove the "static" keyword from each method in the InventoryManager class, they won't let me use any of the methods.

You already asked that in your previous thread, and I already answered it.

When I made the new instance while the methods were static it still did not work.

The whole point of making and using a new instance is to avoid static. The "Java" way to do it is to get rid of all the static keywords (except on the main method) and call all your methods using an instance.

So after changing my InventoryApp class, and removing the static keywords from my other classes this is what my InventoryApp class looks like now:

public class InventoryApp {

   public static void main(String[] args) {

       while(true)
       {
           System.out.println("Enter add to add a product");
           System.out.println("Enter remove to remove a product");
           System.out.println("Enter update to update a product");
           System.out.println("Enter view to view a product");
           System.out.println("Enter quit to quit the menu");
           Scanner sc = new Scanner(System.in);
           String s="";
           s=sc.nextLine();
           if(s.equalsIgnoreCase("quit"))
           {
               break;
           }
           else if(s.equalsIgnoreCase("add")||s.equalsIgnoreCase("update"))
           {
               Product pro=new Product();
               System.out.println("Enter the upc of the product");
               String upc=sc.nextLine();
               pro.setUpc(upc);
               System.out.println("Enter the short detail of the product");
               String sDetail=sc.nextLine();
               pro.setShortDetails(sDetail);
               System.out.println("Enter the long detail of the product");
               String lDetail=sc.nextLine();
               pro.setLongDetails(lDetail);
               System.out.println("Enter the price of the product");
               BigDecimal price=sc.nextBigDecimal();
               pro.setPrice(price);
               System.out.println("Enter the stock of the product");
               int stock=sc.nextInt();
               pro.setStock(stock);

               InventoryManager inventory=new InventoryManager();
               if(s.equalsIgnoreCase("add"))
               {
                   inventory.addProduct(pro);
               }
               else if(s.equalsIgnoreCase("update"))
               {
                   inventory.updateProduct(pro);
               }
           }
           else if(s.equalsIgnoreCase("view")||s.equalsIgnoreCase("remove"))
           {
               System.out.println("Enter the upc of the product");
               String upc=sc.nextLine();
               InventoryManager inventory=new InventoryManager();
               if(s.equalsIgnoreCase("view"))
               {
                   Product pro=inventory.getProduct(upc);
                   if(pro!=null)
                   {
                       System.out.println(pro.toString());
                   }
                   else
                   {
                       System.out.println("No product exist with given upc");
                   }
               }
               else if(s.equalsIgnoreCase("remove"))
               {
                   inventory.removeProduct(upc);
               }

           }


       }

   }
}



and this is the error I receive after running and the program tells me to enter the stock of the product:
Exception in thread "main" java.lang.ClassCastException: java.util.Collections$EmptySet cannot be cast to java.util.List
    at JayJuan.InventoryManager.getProductList(InventoryManager.java:15)
    at JayJuan.InventoryManager.addProduct(InventoryManager.java:45)
    at JayJuan.InventoryApp.main(InventoryApp.java:54)
C:\Users\JonesJ58\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 14 seconds)

Yes, that's the same arror as before. I explained it 3 posts ago.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.