-1

Okay so i am trying to sum up weights of the objects in arraylist together and i've came up to problem with this code. The program gives me error calling "incompatible types: Object cannot be converted to Item" im trying to find solutions but can't find anything useful. also yes, the item is returning an int from .getWeight

int totalWeight = 0;
if (!(items.isEmpty())){
    for (Item i: items){
        totalWeight += i.getWeight();
    }
    return totalWeight;
}
return 0;

let me provide the whole code for further investigation.

import java.util.ArrayList;

public class Packet {
    private ArrayList items;

    public Packet(){
        ArrayList<Item> items = new ArrayList<>();
    }
    public void addItem(Item item){
        items.add(item);
    }
    public int totalWeight(){
        int totalW = 0;
        if (!(items.isEmpty())){
            for (Item i: items){
                totalW += i.getPaino();
            }
            return totalW;
        }
        return 0;
    }
}

edit:: for item class

public class Item {
    private String name;
    private int weight;

    public Item(String name, int weight){
        this.weight = weight;
        this.name = name;
    }
    public String getName(){
        return this.name;
    }
    public int getWeight(){
        return this.weight;
    }

    @Override
    public String toString(){
        return this.name + " (" + this.weight + " kg)";
    }
}

3 Answers3

3

Moreover, there is a good practice to use interface type when declaring new collection. For example, your items list should be declared like this:

private List<Item> items = new ArrayList<>();

The reason is simple - by declaring a collection using an interface type, the code would be more flexible as you can change the concrete implementation easily when needed.

What I mean is that you can easily change your ArrayList to LinkedList for example.

Meshpy
  • 102
  • 6
2

Your issue is here private ArrayList items; You should use <> with arrayList.

private ArrayList<Item> items;

Without <> you have raw type What is a raw type and why shouldn't we use it?

In runtime your items will be equal to ArrayList<Object>. That's why you get Object cannot be converted to Item

Ruslan
  • 6,090
  • 1
  • 21
  • 36
2

In your class Packet, you have to declare items in this way:

private ArrayList <Item> items;

Currently you are creating object items, now you will be creating list of item objects.

  • Thank you, that was actually the reason i was scratching my head red. After editing the code to contain Arraylist I now actually tried running the code and working on it but it gives me nullPointerException – Barack O' Barman Feb 17 '19 at 20:32
  • 1
    @BarackO'Barman In your constructor, you create a different ArrayList with `ArrayList items = new ArrayList<>();`. Instead you should do `this.items = new ArrayList();` to initialize the ArrayList you access in your other method. – Jeppe Feb 17 '19 at 21:16