1. What Are Ambiguity Errors?
2. Example of Ambiguity: Erasure Overload
Problematic code:
class MyGenClass<T, V> { T ob1; V ob2; // Tentativa de sobrecarga void set(T o) { ob1 = o; } void set(V o) { ob2 = o; } }
Error: The attempt to overload the set() method based on the generic parameters T and V appears valid, but causes ambiguity.
3. Reasons for Ambiguity
Example:
MyGenClass<String, String> obj = new MyGenClass<>();
Here, both T and V are replaced by String, making the two versions of set() identical.
Result:
Second Problem: Erasure reduces types to Object.
void set(Object o) { // ... }
This eliminates any distinction between T and V, making overloading impossible.
4. Why Does This Happen?
5. Solution: Avoid Generic Overload
To resolve the ambiguity, use different names for the methods.
Corrected example:
class MyGenClass<T, V> { T ob1; V ob2; void setOb1(T o) { ob1 = o; } void setOb2(V o) { ob2 = o; } }
Here, setOb1() and setOb2() are distinct methods, eliminating the conflict.
6. Conclusion
Ambiguities like this occur because erasure transforms generic parameters into simple types (Object).
To avoid mistakes, follow these practices:
The above is the detailed content of Ambiguity Errors with Generics. For more information, please follow other related articles on the PHP Chinese website!