Shekhar Gulati is a Java Consultant with over 5 years experience.He is currently working with Xebia India an Agile Software Development company.The postings on this site and on his blog are his own and do not necessarily represent opinion of his employer. His own blog is at http://whyjava.wordpress.com/ and you can follow him on twitter here. Shekhar has posted 25 posts at DZone. View Full User Profile

Java Generics Wildcard Capture - A Useful Thing to Know

01.20.2011
| 20996 views |
  • submit to reddit

Recently, I was writing a piece of code where I need to write a copy factory for a class. A copy factory is a static factory that will construct a copy of the same type as that of the argument passed to the factory. The copy factory will copy the state of the argument object into the new object. This will make sure that the newly constructed object is equal to the old one. A copy constructor is similar to a copy factory with just one difference - a copy constructor can only exist in the class containing the constructor whereas copy factory can exist in any other class as well. For example,

// Copy Factory
public static Field getNewInstance(Field field)
// Copy Constructor
public Field Field(Field field)

I choose static copy factory because

  • I didn't have the source code for the class
  • With copy factory I can code to an interface instead of a class.

The class for which I wanted to write copy factory was similar to the one shown below :

public class Field<T> {
private String name;
private T value;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public T getValue() {
return value;
}

public void setValue(T value) {
this.value = value;
}

}

The first implementation of FieldUtils class that came to my mind was as shown below

public static Field<?> copy(Field<?> field) {
Field<?> objField = new Field<?>();//1
objField.setName(field.getName());//2
objField.setValue(field.getValue());//3
return objField;//4
}

The above code will not compile because of two compilation errors. The first compilation error is at line 1 because you can't create an instance of Field<?>.  Field<?> means Field<? extends Object> and when you have ? extends Something you can only get values out of it, you can't set values in it except null. For an object to be useful you should be able to do both, so the compiler does not allow you to create an object. The second compilation error will be at line number 3 and you will get a cryptic error message like this

The method setValue(capture#3-of ?) in the type Field<capture#3-of ?> is not applicable for the arguments (capture#4-of ?)

In simple terms this error message is saying that you are trying to set a wrong value in objField. But what if I had written the following method?

public static Field<?> copy(Field<?> field) {
field.setName(field.getName());
field.setValue(field.getValue());
return field;
}

Will the above code compile? No. You will again get a similar error message as mentioned above. To fix this error we will write a private helper method which will capture the wildcard and assign it to a Type variable. This technique is called Wildcard Capture. I have read this in the Java Generics and Collection book which is a must-read for understanding Java Generics. Wildcard Capture works by type inference.

public static Field<?> copy(Field<?> field) {
return copyHelper(field);
}

private static <T> Field<T> copyHelper(Field<T> field) {
Field<T> objField = new Field<T>();
objField.setName(field.getName());
objField.setValue(field.getValue());
return objField ;
}

Wildcard capture is very useful when you work with wildcards and knowing it will save a lot of your time.

Published at DZone with permission of its author, Shekhar Gulati.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Tags:

Comments

Héctor Hugo Bar... replied on Thu, 2011/01/20 - 7:04am

Hello, Shekhar,

Can you please give an example of what you are supposed to be copying. If you don't need to change value type in copy, I think this code should be simpler. HTH

    public static <T> Field<T> copy(Field<T> field) {
Field<T> objField = new Field<T>();
objField.setName(field.getName());
objField.setValue(field.getValue());
return field;
}

 

Eric Giese replied on Thu, 2011/01/20 - 8:14am

The previous comment is right, just carry the type parameter along.

An explanation to the compiler error:
If you use the ?-wildcard, you are using a COVARIANT type parameter, which works the same way as covariant array works, with one major difference:

Object[] oa = new String[3];
oa[0] = 3; // ArrayStoreException, Runtime error
// generics
List<?> l = new ArrayList[String]();
l.add(4); // Compile-Time Error!

Java arrays are unsafe, because you can use the array type as an input value, so runtime errors can occur. Java generics do not share this design problem, but therefore you cannot use any method with an input type parameter at all, if you are using the ?-wildcard!

Shekhar Gulati replied on Thu, 2011/01/20 - 1:08pm

I agree with you both(Eric and Hector) that using a Type parameter would have solved this problem. But I think designing your classes with wildcards make them more flexible.

Richard Bremner replied on Thu, 2011/01/20 - 5:02pm

In your last example I think you intended to return the new copy "objField", not the original object "field"...

Shekhar Gulati replied on Thu, 2011/01/20 - 5:18pm in response to: Richard Bremner

sorry for the typo. I have updated the post.

Walter Laan replied on Fri, 2011/01/21 - 7:19am in response to: Shekhar Gulati

> But I think designing your classes with wildcards make them more flexible.

Not always true as your example of public static Field<?> copy(Field<?> field just loses type information. It  requires an unchecked cast when called: Field<String> copy = (Field<String>) Factory.copy(stringField). If you use <T> instead <?> the cast isn't needed.

Only use wildcards if you actually don't need the type (you need it to return the correct type).

Vijay Rawat replied on Sat, 2011/12/10 - 8:15am in response to: Walter Laan

Hi Walter,
You are right as an unchecked cast will be required, but the API will be more flexible if we use unbounded declaration.
For example if Field exists as raw type Field and generic type Field , well , in that case, public static Field copy(Field field) will only accept the generic type but public static Field<?> copy(Field<?> field) will also accept the raw type.
In case of public API , unbounded declaration is always preferable. - Effective Java, Joshua Bloch Item 28, page 140.

Jonathan Fuerth replied on Tue, 2012/06/19 - 8:45am

Hi Vijay,

Actually, you're misquoting your source. The advice you're referring to is, "if a type parameter appears only once in a method declaration, replace it with a wildcard." In Héctor's suggestion, the type parameter appears twice: once in the parameter list and once in the return type. Clients of the API can use Héctor's version without thinking about generics at all.

If you flip back three pages in that same book to Page 137, you'll see the advice that best applies to this situation: "Do not use wildcard types as return types. Rather than providing additional flexibility to your users, it would force them to use wildcard types in client code." Or worse--as you admit--an unchecked cast, which defeats compile-time type safety, the primary design goal of Java's generic type system.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.