错误:(32,27)错误:不兼容的类型:对象无法转换为long

use*_*359 4 java android

我是Java的新手.

错误:(40,5)错误:方法没有覆盖或实现超类型的方法
错误:(32,27 )错误:不兼容的类型:对象无法转换为长

    @Override
    public long getItemId(int position) {
        String item = getItem(position);
        return hashMap.get(item);
    }
Run Code Online (Sandbox Code Playgroud)

完整代码如下

package com.javapapers.android.listview;

import android.content.Context;
import android.widget.ArrayAdapter;
import java.util.HashMap;
import java.util.List;

public class SimpleArrayAdapter extends ArrayAdapter {

    Context context;
    int textViewResourceId;
    private static final String TAG = "SimpleArrayAdapter" ;
    HashMap hashMap = new HashMap();

    public SimpleArrayAdapter(Context context, int textViewResourceId,
                              List objects) {
        super(context, textViewResourceId, objects);
        this.context = context;
        this.textViewResourceId = textViewResourceId;
        for (int i = 0; i < objects.size(); ++i) {
            hashMap.put(objects.get(i), i);
        }
    }

    @Override
    public long getItemId(int position) {
        String item = getItem(position);
        return hashMap.get(item);
    }

    @Override
    public boolean hasStableIds() {
        return true;
    }

    @Override
    public void add(String object){
        hashMap.put(object,hashMap.size());
        this.notifyDataSetChanged();
    }
}
Run Code Online (Sandbox Code Playgroud)

azu*_*rog 6

您遇到的问题源于hashMap.get(item)返回一个事实Object,但您的方法签名指定您需要返回一个long.

public long getItemId(int position) {   // you say you will return a long
    String item = getItem(position);
    return hashMap.get(item);           // but try to return an Object
}
Run Code Online (Sandbox Code Playgroud)

Java中没有办法让JVM 自动将任意随机Object转换为a long,因此编译器会给你这个错误.

有几种方法可以解决这个问题.

错误的方法

第一个(坏的)方法是你从地图获得的变量强制转换为long:

public long getItemId(int position) {   // you say you will return a long
    String item = getItem(position);
    return (long)hashMap.get(item);     // and you return a long
}
Run Code Online (Sandbox Code Playgroud)

这将使你的代码编译,但你在这里有效地做的是承诺编译器,你真的,非常确定你放入的Map是一个Long.此时,编译器将尝试将其取消Long装入a long并返回它.如果确实Long如此,那将是有效的,如果不是,你将被ClassCastException抛出.

正确的方式

在较新版本的Java中,有一种称为泛型的东西.使用泛型,您可以指定允许的对象类型,可以在定义时添加到容器中,如下所示:

// create a HashMap where all keys are Objects and all values are Longs
Map<Object, Long> hashMap = new HashMap<>();

public long getItemId(int position) {   // you say you will return a long
    String item = getItem(position);
    return hashMap.get(item);           // no cast is required
}
Run Code Online (Sandbox Code Playgroud)

现在,编译器只允许将类型的值Long存储在地图中,并且您get()从中的任何内容都将自动成为a Long,从而消除了转换返回类型的需要(和危险).