当我确定数据是整数时,'无法从Object转换为int'错误 [英] 'Cannot cast from Object to int' error when I'm sure the data is an integer

查看:566
本文介绍了当我确定数据是整数时,'无法从Object转换为int'错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我确信我在做一些非常愚蠢和基本的事情,但我似乎无法解决这个问题。我基本上有一个方法需要一堆数字,有些工作并返回一个整数列表。

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.

然后我把那个列表发送给一个方法来做还有一些工作,但是当我收到错误时,因为JVM认为它是一个对象。这是一个简单的例子(我正在编辑它,所以你得到的想法,它不是超长):

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

起初我尝试用norm_data.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?)

推荐答案

演员整数

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

或者更好的是,make normalizer_list a List< Integer> ,然后接受 do_some_work 方法中的整数列表。

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

这篇关于当我确定数据是整数时,'无法从Object转换为int'错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆