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)";
}
}