nitowa
nitowa

Reputation: 1107

The type parameter is X hiding the type X

I'm trying to implement this code. Rent is a subclass of Transaction.

import java.util.LinkedList;
public class TransactionList<Transaction> extends LinkedList { //TransactionList: warning: The type parameter Transaction is hiding the type Transaction

public TransactionList<Rent> getRentTransactions(){
    TransactionList<Rent> rentList = new TransactionList<Rent>();

    for(Transaction t : this){ //this: error: Type mismatch: cannot convert from element type Object to Transaction
        if(t instanceof Rent){ 
            t = (Rent) t; //this: warning: Type mismatch: cannot convert from Rent to Transaction
            rentList.add((Rent) t);// whole statement: warning: Type safety: The method add(Object) belongs to the raw type LinkedList. References to generic type LinkedList<E> should be parameterized
        }
    }
    return rentList;
}

I'm really lost with this, I'm absolutely sure this code is type safe as any given TransactionList will always contain Transaction or a subclass of Transaction.

However if I change the for statement to

for(Object t : this)

it will compile. However all Objects held by the returned TransactionList will be of the type Object, and unable to be casted to Rent Objects.

Upvotes: 0

Views: 380

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280102

You more than likely meant

public class TransactionList extends LinkedList<Transaction> { 

What you had

public class TransactionList<Transaction> extends LinkedList { 

declares a new type variable named Transaction. So it's equivalent to

public class TransactionList<T> extends LinkedList { 

and the parent class declaration is raw. Read this to understand when and when not to use raw types. In this case, the type parameter that you've named Transaction is hiding a concrete type also named Transaction.

You can't do this

for(Transaction t : this)

because this is an Iterable through inheritance (extends LinkedList), but since it's a raw type, the type is erased to Object. An Object is not assignment compatible with the type parameter Transaction.

Upvotes: 2

Related Questions