I am trying to sum up an ArrayList
to an integer.
On the sum += list.get(i);
line I get an error:
The operator += is undefined for the argument type(s) double, Object
JTable j = new JTable(data, columnNames);
List<Object> list = new ArrayList<>();
for (i = 0; i < j.getModel().getRowCount(); i++) {
list.add(j.getModel().getValueAt(i, 1));
}
int sum = 0;
for (int i = 0; i < list.size(); i++) {
sum += list.get(i);
}
System.out.println(sum);
What can I do to sum up the ArrayList
to an integer?
getValueAt
returns an Object
. If you know it's an Integer
, you need to explicitly cast it so that Java can treat it as such. E.g.:
List<Integer> list = new ArrayList<>();
for(i = 0;i<j.getModel().getRowCount();i++)
{
list.add((Integer) j.getModel().getValueAt(i,1));
}
Now that list
is a List<Integer>
, list.get
will return an Integer
, not an Object
, and your second for
loop should work just fine.
EDIT:
According to the comment, the value in model is actually a String
not an Integer
. You'll have to convert it to an Integer
yourself:
List<Integer> list = new ArrayList<>();
for(i = 0;i<j.getModel().getRowCount();i++)
{
list.add(Integer.valueOf((String) j.getModel().getValueAt(i,1)));
}