Lostsoul
Lostsoul

Reputation: 25999

'Cannot cast from Object to int' error when I'm sure the data is an integer

I'm sure I'm doing something really dumb and basic here but I can't seem to figure this out. I basically have a method that takes a bunch of numbers, does some work and returns a List of integers.

I then take that list and send it to a method to do some more work on but when I was getting errors because JVM thinks its an object. Here's a simple example(I'm editing it a bit so you get the idea and its not super long):

public static List normalizer_list(double[] data) {
    List normalizer_list = new ArrayList();
    for (double current_data : data) {
        Integer modified_data = (int) (current_data *1000);
        normalizer_list.add(modified_data);
    }
    return normalizer_list;
}


private static void do_some_work(List normalizer_list) {
    // TODO Auto-generated method stub

    for (int i = 0; i < norm_data.size(); i++) {
        Integer current_norm_data = (int) normalizer_list.get(i);

At first I tried to do math with norm_data.get(i) but it gave me errors because it thought it was a object, so I tried to cast it to an Integer and it says I can't do that. What am I doing wrong(is it the way I'm using the list?)

Upvotes: 0

Views: 9452

Answers (3)

BoschAlex
BoschAlex

Reputation: 241

You can use Integer.valueOf();

 Integer modified_data = Integer.valueOf(current_data *1000);

Upvotes: 0

Matt Harrison
Matt Harrison

Reputation: 358

Maybe you should look at using List to put your data in - then getting rid of all the casting?

Upvotes: 0

Dilum Ranatunga
Dilum Ranatunga

Reputation: 13374

Cast as an Integer:

Integer current_norm_data = (Integer) norm_data.get(i)

Or better yet, make normalizer_list a List<Integer>, then accept an integer list in the do_some_work method.

Upvotes: 8

Related Questions