Java中,简化检查,如果int数组包含INT [英] Java, Simplified check if int array contains int

查看:128
本文介绍了Java中,简化检查,如果int数组包含INT的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我的队友一直在说,我可以让我的code。通过使用检查,如果一个int数组包含一个int不同的方式短,虽然他不会告诉我它是什么:P

Basically my mate has been saying that I could make my code shorter by using a different way of checking if an int array contains an int, although he won't tell me what it is :P.

电流:

public boolean contains(final int[] array, final int key) {
    for (final int i : array) {
        if (i == key) {
            return true;
        }
    }
    return false;
}

也有试过,但它总是出于某种原因返回false。

Have also tried this, although it always returns false for some reason.

public boolean contains(final int[] array, final int key) {
    return Arrays.asList(array).contains(key);
}

谁能帮助我?

感谢您。

推荐答案

这是因为 Arrays.asList(阵列)收益列表< INT [] > 阵列参数被视为一个值,你想换行(整数数组的你列表),而不是作为可变参数。

It's because Arrays.asList(array) return List<int[]>. array argument is treated as one value you want to wrap (you get list of arrays of ints), not as vararg.

请注意,它的确实的使用对象类型(而不是原语)的工作:

Note that it does work with object types (not primitives):

public boolean contains(final String[] array, final String key) {
    return Arrays.asList(array).contains(key);
}

甚至是:

public <T>  boolean contains(final T[] array, final T key) {
    return Arrays.asList(array).contains(key);
}

但你不能有列表&LT; INT方式&gt; 键,自动装箱不会在这里工作。

But you cannot have List<int> and autoboxing is not working here.

这篇关于Java中,简化检查,如果int数组包含INT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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