-3

So I decided to use ArrayList but now I want to change it to Array. I'm trying to see if this works with Array only instead of ArrayList. Can anyone sugest some way to do it nice and simple? I want to change it but I searched the internet for some way to do it but the information I found it didn't work for my case.

public class ProductManager {
    private List<Product> listOfProduct;
    public ProductManager() {
        this.listOfProduct= new ArrayList<>();
    }

    public int addProduct(Product p) {
        this.listOfProduct.add(p);
        return count();
    }

    public int count() {
        return this.listOfProduct.size();
    }

    public Product getProduct(int index) {
        if (index < 0 || index >=count()) {
            return null;
        }
        return this.listOfProduct.get(index);
    }

    public boolean removeProduct(int id) {
        int index = -1;
        for (int i = 0, n = count(); i < n;i++) {
            if(this.listOfProduct.get(i).getId() == id) {
                index = i;
                break;
            }
        }
        if(index != -1) {
            this.listOfProduct.remove(index);
            return true;
        }
        return false;
    }

Some suggestions are appreciated :) Thank you!

ascripter
  • 5,665
  • 12
  • 45
  • 68
  • 2
    Why change it to array? It's rarely necessary or smart to use arrays over collections. – Kayaman May 22 '18 at 15:41
  • 2
    90% of the code you have posted seems to be completely unrelated to your problem. You may consider posting a [mcve] instead. – assylias May 22 '18 at 15:42
  • 2
    Possible duplicate of [Convert ArrayList to String\[\] array](https://stackoverflow.com/questions/5374311/convert-arrayliststring-to-string-array) – Jan Ossowski May 22 '18 at 15:47
  • Ok. So i will look over there for answers. Thank you. – Jack Duvall May 22 '18 at 16:00
  • You need to learn how to format your code. Indentation really helps with understanding what is executing and when. Both IntelliJ and Eclipse offer automatic formatting options (in the former, default Mac keybind is Command-Option-L and in the latter, you go to Save Actions under preferences). – ifly6 May 22 '18 at 16:08

2 Answers2

1

Well, it looks like you're getting started with basic Java.

After reviewing your code, I'd like to share with you some points to improve.

First, look at your problem, the number of Product is dynamic, and you don't know exactly the number of how many Product to be added into the store, which is ProductManager. It means you should use a dynamic data structure, and your code uses List, this is correct. Only use array when you know exactly number of elements to allocate; otherwise, go for List.

To remove an element of Collection, which is List as in your code, it's better to use Iterator, in which you can remove element while looping. Here it is.

public Product removeProduct(int id) {
    Iterator<Product> iterator = productList.iterator();
    Product found = null;

    while(iterator.hasNext()) {
        Product product = iterator.next();
        if(product.getId() == id) {
            found = product;
            iterator.remove(); // remove on the fly
        }
    }

    // return pointer to removed product
    // Note: it can be NULL
    return found;
}

For removeProduct method signature (return value), you can modify to return boolean value as you wish.

Instead of reading price value as string then parse to Float manually, you can directly use scanner.nextFloat() method. Read more about Scanner here.

To calculate the whole inventory price value, just loop and sum all the price.

public float getInventoryValue() {
    int total = productList.size();
    float sum = 0.0f;

    for(int i = 0; i < total; ++i) {
        // simple, easy loop
        sum += productList.get(i).getPrice();
    }

    return sum;
}

I guess that's done for your question.

If you insist on converting from List to array, you can either:

  • Initialize a new static array with known size from List.size(), then assign elements.
  • Or, quick dirty trick Product[] productArr = (Product[]) productList.toArray();

Last but not at least, you should write question and format code nicely; otherwise, others will vote down and close your questions :)

You're doing great, just a little more!

Pete Houston
  • 14,931
  • 6
  • 47
  • 60
  • I'm not sure `productList.toArray()` will work, I think it would have to be `Product[] productArr= arrlist.toArray(new Product[productList.size()]);` or some such. `toArray(T[] a)` is the method, I don't think there's an option for no arguments (unless this is a new thing with Java 10 I'm not aware of). That said, good answer! – Grey Haven May 22 '18 at 16:23
  • thank you guys! Appreciate your help and suggestions! – Jack Duvall May 22 '18 at 16:28
  • @GreyHaven you can refer to Java doc https://docs.oracle.com/javase/8/docs/api/java/util/Collection.html#toArray-- , but it's not safe if it has some other references (pointer). – Pete Houston May 22 '18 at 16:29
  • Oh, nice! Awesome, didn't realize that. – Grey Haven May 22 '18 at 16:30
0

I'd check out some java documentation, this is a pretty well known thing. https://www.tutorialspoint.com/java/util/arraylist_toarray.htm

But a simple for loop would also do it.

Product[] convertArrayListToArray(ArrayList<Product> arrList){
    Product[] arr = new Product[arrList.size()];
    for(int i = 0; i < arrList.size(); i++){
        arr[i] = arrList.get(i);
    }
    return arr;
}
Grey Haven
  • 380
  • 2
  • 13
  • If the types are guaranteed, you can just use `System.arraycopy` – ifly6 May 22 '18 at 16:07
  • Fair. I like the `toArray()` method a bit more just because it's a bit more intuitive of what's going on, fewer arguments etc. But yes, `arraycopy` is definitely legit. – Grey Haven May 22 '18 at 16:09
  • But you don't use `toArray`, you're manually copying each element over. Using `toArray` would look like this: `list.toArray(new String[list.size()]);` – ifly6 May 22 '18 at 16:11
  • Oh, yeah, totally. I was wanting to go over how to manually do it. Figured I'd let the link I provided speak for the `toArray(T[] a)` method. – Grey Haven May 22 '18 at 16:12
  • thank you guys for the guidance! :) wish you all a nice day! – Jack Duvall May 23 '18 at 10:38