-2
protected Collection<Node> createBucket() {
    return new LinkedList<>();
}

/**
 * Returns a table to back our hash table. As per the comment
 * above, this table can be an array of Collection objects
 *
 * BE SURE TO CALL THIS FACTORY METHOD WHEN CREATING A TABLE SO
 * THAT ALL BUCKET TYPES ARE OF JAVA.UTIL.COLLECTION
 *
 * @param tableSize the size of the table to create
 */
private Collection<Node>[] createTable(int tableSize) {
    Collection[] table = new Collection[tableSize];
    for (int i = 0; i < tableSize; ++i) {
        table[i] = createBucket();
    }
    return table;
}

For the createTable() method, the return type is Collection<Node>[] but ended up what the function return was Collection[] and this piece of code can still successfully be compiled and executed. My question is the compiler performs type checking based on static type but the static type of table which is Collection[] doesn't match the return type Collection<Node>[] why is the code still able to be compiled?

I read through different questions at and understand the fact that if raw type is used then generics are turned off. Java assumes that the generic type is Object so I thought table should be Collection<Object> and therefore the code will not be compiled too however it still works so can someone correct my understanding?

3
  • 1
    It works because of Java's type erasure, treating Collection<Node>[] and Collection[] as the same at runtime. Unchecked conversions allow assigning LinkedList<Node> to Collection due to raw types. Java's backward compatibility enables interaction between generic and non-generic code with less type safety.
    – Hagelslag
    Commented Jul 5 at 8:29
  • Raw types are a legacy thing inherited from Java versions prior to 1.5, which was released 20 years ago, so there is really no excuse for using raw types today. Your IDE should have warned you about use of raw types.
    – k314159
    Commented Jul 5 at 10:18
  • @k314159 so nowadays raw types are almost not used right, anyways I had changed my approach so thanks for notifying me abt this scenario
    – Pius
    Commented Jul 5 at 13:08

0

Browse other questions tagged or ask your own question.