Can someone explain the declaration of these java generic methods? - java

I'm reading "Generics in the Java Programming Language" by Gilad Bracha and I'm confused about a style of declaration. The following code is found on page 8:
interface Collection<E>
{
public boolean containsAll(Collection<?> c);
public boolean addAll(Collection<? extends E> c);
}
interface Collection<E>
{
public <T> boolean containsAll(Collection<T> c);
public <T extends E> boolean addAll(Collection<T> c);
// hey, type variables can have bounds too!
}
My point of confusion comes from the second declaration. It's not clear to me what the purpose the <T> declaration serves in the following line:
public <T> boolean containsAll(Collection<T> c);
The method already has a type (boolean) associated with it.
Why would you use the <T> and what does it tell the complier?
I think my question needs to be a bit more specific.
Why would you write:
public <T> boolean containsAll(Collection<T> c);
vs
public boolean containsAll(Collection<T> c);
It's not clear to me, what the purpose of <T> is, in the first declaration of containsAll.

As far as I can tell, in this case <T> doesn't provide anything useful at all. It creates a method that is completely functionally equivalent to those using the wildcard instead.
Here are a couple of examples where it would be useful:
public List<?> transform(List<?> in);
//vs
public <T> List<T> transform(List<T> in);
In the above, you can correlate the return type with the input type. The first example cannot correlate the runtime type of the two wildcards.
public void add(List<?> list, Object obj);
//vs
public <T> void add(List<? super T> list, T obj);
In the above, the first method won't even be able to add obj to list since it can't be deemed to be type safe. The generic parameter in the second ensures that list can hold whatever type obj is.

The method already has a type (boolean) associated with it.
That is the return type. The full type of the method is “method that takes a Collection<T> (for some T) parameter and returns a boolean”.
And this is where T comes in: the parameter of the function uses it. In other words, this method can be called with different types as argument. The only restriction of these types is that they must implement the Collection<T> interface, which itself relies on a generic argument T (the type of the objects stored in the collection).

The ? is simply a wildcard. It means that the method will accept a Collection of any type.
The <T> is a type parameter for the method. It is essentially assigning the wildcard a name which can then be referred to elsewhere in the method declaration and definition.
A better illustration of the difference would be if the return type of the method varied based on the type that was passed in.
Say you started with a method like
Object getRandomElement( Collection<?> c )
This will accept any Collection, but there's no way to constrain its return type. So a caller would have to cast the result back to whatever type it expected -- which should work, but raises unsafe type-conversion warnings.
With a type parameter you would instead write
<T> T getRandomElement( Collection<T> c )
In this case, if you call this method with a Collection<String>, the compiler knows that it will return a String.

<T> as used here (in method declaration, before return type) is a generic type declaration. You can define new generic type for use within a method: http://download.oracle.com/javase/tutorial/java/generics/genmethods.html

Try compiling it without the <T>.
Basically, it's telling the compiler that this method contains a generic. It isn't required in the first example because ? is a special case, and the second method is referencing the type defined in the Interface itself.
On an unrelated note, public is not required in an Interface. Methods in an interface are public by default, so can save you a bit of typing.

It declares the generic type T used by the method. While the generic type E is the same for the whole interface T is limited to the method it is declared for.

Related

What is the purpose of generics before return type

For example, in the following code
public <U extends Number> void inspect(U u){
// Some method
}
what is the purpose of (what is this line doing or how is it read)
that comes just before the return type
This is the syntax that makes your method (as opposed to your class) generic.
Methods of regular and generic classes can be made generic on their own type parameters. In this case, your inspect method is generic on U, which must be a type extending from Number.

What's the difference between <T> T vs T in the return type of a method?

I have a method, like this,
public <T> T doSomething(Class<T> T) {
return T.newInstance();
}
I can also do the same like this,
public T doSomething(Class<T> T) {
return T.newInstance();
}
Is there any difference between these two? Please ignore T.newInstance(), I'm basically going to create a new instance of T somehow and return it.
thanks,
sam
What's the difference between <T> T vs T in the return type of a method?
There is no <T> T. The <T> is not part of the return type; it's a separate thing, indicating the type parameter. (You can also have public <T> void ....)
In the version with <T>, you're declaring T as a type parameter of the method, and the T in the argument and the return-type are referring to that type parameter.
In the version without <T>, you're not declaring T as a type parameter of the method, so it's most likely a type parameter of the containing class or another containing scope. (Alternatively, someone may have named an actual class or interface T, in which case you should give that person a talking-to.)
If both versions compile, then the second is probably the one you want: you probably want to be using the class's type parameter T, rather than adding a new one that hides it. (And if you really do want a new type parameter unrelated to your class's type parameter, then you should use a new name for it to avoid confusion.)
In the first example, you declare a generic method doSomething with its own type parameter <T>. If it's in a generic class, then this <T> is separate from any type parameters that the class may have (even another <T>!).
In the second example, you don't declare a generic type parameter on doSomething. If the class defines <T>, then this method simply uses it. If it doesn't, then T is unrecognized and a compiler error results.
Second option will work only if T is declared as a class generic type. If class doesn't define any generic type and only its member function accepts/returns generic type , you need to explicitly declare it in function declaration.

Understanding: public static <T> int max(List<T> list, Comparator<? super T> c) please

Im supposed to make a method that returns the max value of any list, I guess this is a generic method. But I dont understand the parameters, could anyone please explain me?
Also I made a iterator that i will use in the solution to run through the list, but when i make a instance of the iterator this method gives me the following error: "#nameofclass can not be referenced from a static context", then how do I make a instance here? ( its supposed to be static for some reason) I would appreciate any help!
public static <T> int maks(List<T> list, Comparator<? super T> c)
{
// return max in a list
}
The following is a pretty typical generic method declaration:
public static <T> int max(List<T> list, Comparator<? super T> c) {
:
:
}
There are two overall kinds of generic declarations: 1) generic class/interface, and 2) generic method. Once you're comfortable with these two idioms, you're well on your way to having a good understanding of generics. The raw type declaration for this is:
public static int max(List list, Comparator c) {
:
:
}
The raw type declaration makes it easy to see that this method returns a value to its caller of type int. The method accepts two parameters: a List instance and a Comparator instance.
The trouble with the raw type declaration is that it is not safe. Why? Because both List<E> and Comparator<T> are generic classes that have been defined with a formal generic type parameter. If you use a generic class, but then don't specify its parameter (as in the declaration above) you lose all the type safety and expressiveness that generics provide for you.
A generic method is characterized by the following method:
public <T> MyType myMethodName( /* parameters */) { ... }
Notice that a generic method is declared with its type parameters in the method declaration and that the type parameters come immediately before the return type. This is standard.
In this case <T> indicates an unbounded type parameter for your method. Wherever T appears in your method, the actual type parameter passed to your method will take the place of T. It is common, but not necessary, to make the method parameters depend upon T (but T can appear anywhere inside the method body that a type declaration can appear -- with some exceptions necessitated by type erasure).
In your example, the parameters list is ...
(List<T> list, Comparator<? super T> c)
The first parameter specified that the instance list passed to your method will have the type List. Because T is the generic method type parameter listed in your method declaration, you can imagine that it is substituted for the actual type parameter that was passed to your method, eg. List<String> list.
The second parameter is a bit more complex. It is a bounded wildcard type parameter. The sematics for ? are "any type" and the semantics for super are "any class that is the same class or a super class of". Therefore the second parameter reads as "any type that is the same type or a super type of the actual type parameter T that was passed to your method."
There is a mnemonic that is apt for bounded wildcard types: PECS. Producer extends, Consumer super. Comparators are always consumers of their instances, and so the right way to specify them in a parameter list is as shown in your method declaration.
You have List list and Comparator c, so why not just:
Collections.max(list, c);
-it will return max element in a List or any other Collection.
Though I don't understand why you want to return int when looking for max value in a generic list -maybe you're looking for its' index?

Java What is difference between generic method and a method object as a parameter?

What are advantage between a generic method and a method just accepts Object? How does it ensures type safety?
For example: What difference does it make when define my interface in either of the form mentioned in below code snippet?
public interface MyInterface {
public <MT> String myMethod(MT t);
}
OR
public interface MyInterface {
public String myMethod(Object t);
}
In my opinion Generic methods are advantageous only when we type bound around it.. for example type parameter should of Serializable class like. Otherwise it doesn't make sense.. looking for more insight
public interface MyInterface {
public <MT extends Serializable> String myMethod(MT t);
}
A method is usually made generic to ensure that two arguments are compatible with each other, or to return a value whose type depends on the generic type of the method.
For example,
public static <T> void sort(List<T> list, Comparator<? super T> c)
makes sure the type of the list and the type of the comparator are compatible, which wouldn't necessary be the same if the signature was
public static void sort(List list, Comparator c)
In the following example, the returned value's type depends on the generic type of the method:
public static <T extends Object & Comparable<? super T>> T min(Collection<? extends T> coll)
which allows doing:
List<Integer> intList = ...;
Integer min = Collections.min(intList);
If the method was
public static Comparable T min(Collection coll)
you would have to do
Integer min = (Integer) Collections.min(intList);
and you wouldn't have any warning from the compiler if you changed the code to
Long min = (Long) Collections.min(intList);
It can be also nice to see what it means from the compile/runtime point of view.
If you use generics, then the compiler generates the necessary code during compilation and you would't do runtime casting on your relevant objects and/or type checking.
On the other hand, if you use only the Object class as a generic type, you would probably end up having slightly less code (since the compiler wouldn't be generating anything) but you would need to take care of runtime type safety and casting by yourself.
You are partially correct. Generic method and method as a object look like same in some context but the major difference is how compiler handles both
For the object as params type conversion is done based on the typecasting basically it is being handled runtime but for the generic type compile time only it is being handled.
Compile time handling is much better than the run time one. So the generic method is good to use as compare to object as a parameter in your context
Generic method restricts the type of parameter that can be passed to the method. That brings in more cohesive code which limits the input that it can work on, and thus can be reasonably assumed to have certain features.
For e.g
public interface MyInterface {
public [MT extends BaseClass] String myMethod(MT t);
}
Here you always know that all the methods that are applicable for BaseClass are applicable to t in this method.

Java : What is - public static<T> foo() {...}?

I saw a java function that looked something like this-
public static<T> foo() {...}
I know what generics are but can someone explain the in this context? Who decides what T is equal to? Whats going on here?
EDIT: Can someone please show me an example of a function like this.
You've missed the return type out, but apart from that it's a generic method. As with generic types, T stands in for any reference type (within bounds if given).
For methods, generic parameters are typically inferred by the compiler. In certain situations you might want to specify the generic arguments yourself, using a slightly peculiar syntax:
List<String> strings = Collections.<String>emptyList();
In this case, the compiler could have inferred the type, but it's not always obvious whether the compiler can or can't. Note, the <> is after the dot. For syntactical reasons the type name or target object must always be specified.
It's possible to have generic constructors, but I've never seen one in the wild and the syntax gets worse.
I believe C++ and C# syntaxes place the generic types after the method/function name.
The context is a generic method as opposed to a class. The variable <T> applies only to the call of the method.. The Collections class has a number of these; the class itself is not generic, but many of the methods are.
The compiler decides what T is equal to -- it equals whatever gets the types to work. Sometimes this is easier then others.
For example, the method static <T> Set<T> Collections.singleton(T o) the type is defined in the parameter:
Collections.singleton(String T)
will return a Set<String>.
Sometimes the type is hard to define. For example sometimes there is not easily enough information to type Collection.emptyList(). In that case you can specify the type directly: Collection.<String>emptyList().
T it's the formal type parameter wich will be replaced by the actual type
argument used at the instantiation of the object.
For example, here is the List and Iterator definitios in package java.util:
public interface List<E>{
void add(E x);
Iterator<E> iterator();
}
public interface Iterator<E>{
E next();
boolean hasNext();
}
Then you can instantiate a List this way:
List<String> ls = new ArrayList<String>()
Where you might imagine that List stands for a version of List where E has
been uniformly replaced by String:
public interface StringList{
void add(String x)
Iterator<String> iterator();
}

Categories

Resources