简体   繁体   中英

For loop with generic parameters in Java

Short question - how should it look like to work?

private <T> boolean hasElement(T array, T element) {
    for (T el : array) {
        if (el.equals(element)) {
            return true;
        }
    }
    return false;
}

Now it shows error in line where for loop starts.

private <T> boolean hasElement(T[] array, T element) {
                                ^^

try this

private <T> boolean hasElement(T[] array, T element) {
    for (T el : array) {
        if (el.equals(element)) {
            return true;
        }
    }
    return false;
}

not that though generic version is better still this version will compile and work too

private boolean hasElement(Object[] array, Object element) {
    for (Object el : array) {
        if (el.equals(element)) {
            return true;
        }
    }
    return false;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM