散列图不适用于int

散列图不适用于int

本文介绍了散列图不适用于int,char的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





  public HashMap< char,int> buildMap(String letters)
{
HashMap< char,int> checkSum = new HashMap< char,int>();

for(int i = 0; i< letters.length(); ++ i)
{
checkSum.put(letters.charAt(i),primes [一世]);
}

return checkSum;
}

我收到与不恰当类型相关的错误。我通过分别使用Character和Integer来代替char和int来解决我的问题。但是,我无法弄清楚为什么HashMap无法处理原始数据类型。

解决方案

通用参数can只绑定到引用类型,而不是基元类型,所以你需要使用相应的包装类型。尝试使用 HashMap< Character,Integer> 来代替。

这是由于。 Java从一开始就没有泛型,所以 HashMap< Character,Integer> 确实是一个 HashMap< Object,Object> 。编译器会执行一些额外的检查和隐式转换以确保不会将错误类型的值放入或获取错误的类型,但在运行时只有一个 HashMap

其他语言特化类型,所以在C ++中,一个向量< bool> 与内部的 vector< my_class> 非常不同,它们没有共同的 vector < / code> super-类型。 Java定义了一些东西,所以 List< T> List ,无论 T 是为了向后兼容预先通用的代码。这种向后兼容性要求必须有一个用于泛型类型的所有参数化的单个实现类,这防止了模板专门化,这将允许泛型参数绑定到基元。


In java when I use the following :-

public HashMap<char, int> buildMap(String letters)
{
    HashMap<char, int> checkSum = new HashMap<char, int>();

    for ( int i = 0; i < letters.length(); ++i )
    {
        checkSum.put(letters.charAt(i), primes[i]);
    }

    return checkSum;
}

I get errors related to inappropriate types. I solved my problem by using Character and Integer instead of char and int respectively. However, I'm having trouble figuring out why HashMap fails to be able to deal with primitive data types.

解决方案

Generic parameters can only bind to reference types, not primitive types, so you need to use the corresponding wrapper types. Try HashMap<Character, Integer> instead.

This is due to type erasure. Java didn't have generics from the beginning so a HashMap<Character, Integer> is really a HashMap<Object, Object>. The compiler does a bunch of additional checks and implicit casts to make sure you don't put the wrong type of value in or get the wrong type out, but at runtime there is only one HashMap class and it stores objects.

Other languages "specialize" types so in C++, a vector<bool> is very different from a vector<my_class> internally and they share no common vector<?> super-type. Java defines things though so that a List<T> is a List regardless of what T is for backwards compatibility with pre-generic code. This backwards-compatibility requirement that there has to be a single implementation class for all parameterizations of a generic type prevents the kind of template specialization which would allow generic parameters to bind to primitives.

这篇关于散列图不适用于int,char的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-27 18:08