简体   繁体   中英

In java generic programming, is the Object class upper bound or lower bound of the parameter type without wildcard?

when answering the question Creating generic array in Java via unchecked type-cast , newacct said

(The lower bound of Bar is Object in this question. In a case where the lower bound of Bar is something else, replace all occurrences of Object in this discussion with whatever that bound is.)

Here is newacct's code:

class Foo<Bar> {
    Bar[] bars = (Bar[])new Object[5];
    public Bar get(int i) {
        return bars[i];
    }
    public void set(int i, Bar x) {
        bars[i] = x;
    }
    public Bar[] getArray() {
        return bars;
    }
}

I wonder whether Object is the upper bound or lower bound of Bar . I think that Foo<Bar> is short for Foo<Bar extends Object> , so Object should be the upper bound of Bar , am I wrong?

Given a type variable declaration <T extends TypeName> , TypeName is the upper bound of T . Technically, I think it's just the bound , since the upper/lower distinction is only made for wildcards . Additionally, if no bound is specified, then Object is assumed , so you're right that Object is the bound of Bar in the example.

I think newacct just misspoke when they wrote the answer and meant to say 'upper bound' instead of 'lower bound'.

Edit : Also, when talking about the particular construct in the referenced Q&A, it's useful to point out that the erasure of a type variable is the erasure of its left-most bound which is the importance of replacing the element type used for the array creation with the type used in the bound. For example, given a complex type variable declaration <T extends Comparable<T> & Serializable> , the erasure of T would be Comparable , so you would use Comparable[] or Comparable<?>[] .

You can define the lower bound as follows in generics as well.

class Foo<T extends Bar> {
T[] bars = (T[])new Object[5];
public T get(int i) {
    return bars[i];
}
public void set(int i, Bar x) {
    bars[i] = x;
}
public T[] getArray() {
    return bars;
}

}

So you can create a Foo object with any class that extends Bar.

No, you cannot use Object typed instances and lower bound is Bar and upper bound is any class that extends Bar class .

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