Java: Array of primitive data types does not autob

2019-01-02 23:47发布

I have a method like this:

public static <T> boolean isMemberOf(T item, T[] set)
{
    for (T t : set) {
        if (t.equals(item)) {
            return true;
        }
    }
    return false;
}

Now I try to call this method using a char for T:

char ch = 'a';
char[] chars = new char[] { 'a', 'b', 'c' };
boolean member = isMemberOf(ch, chars);

This doesn't work. I would expect the char and char[] to get autoboxed to Character and Character[], but that doesn't seem to happen.

Any insights?

10条回答
够拽才男人
2楼-- · 2019-01-03 00:30

You could use reflection to get a method that works for all types of arrays, but you would lose type safety, so this is probably not what you want.

import java.lang.reflect.Array
public static boolean isMemberOfArray(Object item, Object array)
{
    int n = Array.getLength(array)
    for (int i = 0; i < n; i++) {
        if (Array.get(array, i).equals(item)) {
            return true;
        }
    }
    return false;
}
查看更多
男人必须洒脱
3楼-- · 2019-01-03 00:33

A simpler way to do this is

char ch = 'a';
String chars = "abc";
boolean member = chars.indexOf(ch) >= 0;
查看更多
forever°为你锁心
4楼-- · 2019-01-03 00:38

Correct, there is no autoboxing for arrays (which results in weirdness in cases like int[] ints; ...; Arrays.asList(ints) - asList returns a List containing a single Object, the array!)

Here's a simple utility to box an array.

public static Integer[] boxedArray(int[] array) {
    Integer[] result = new Integer[array.length];
    for (int i = 0; i < array.length; i++)
        result[i] = array[i];
    return result;
}

You will need a different version for each primitive type, of course.

查看更多
Explosion°爆炸
5楼-- · 2019-01-03 00:42

There is no autoboxing for arrays, only for primitives. I believe this is your problem.

查看更多
神经病院院长
6楼-- · 2019-01-03 00:42

As others have mentioned, there is no autoboxing for arrays of primitives. If you want to use your method with primitive arrays, you will need to provide an overload for each primitive type. This seems to be the standard way of doing things in the class libraries. See the overloads in java.util.Arrays, for example.

查看更多
看我几分像从前
7楼-- · 2019-01-03 00:44

Why would char[] be boxed to Character[]? Arrays are always reference types, so no boxing is required.

Furthermore, it would be hideously expensive - it would involve creating a new array and then boxing each char in turn. Yikes!

查看更多
登录 后发表回答