Generics without collection

I have a method that usually takes an item from a list and has a signature:

myMethod(T item) 

I want to use this method, but I know that I am sending a method.

 SpecificItem myItem = new SpecificItem(); myMethod((T) myItem); 

This is not very good with me. Is this a sign of bad code?

+4
source share
5 answers

myMethod defined in a common class, somewhat reminiscent of:

 public class MyClass<T> { T myItem; public void myMethod(T item) { // do Something with item } public T myOtherMethod() { myMethod(myItem); // casting is not necessary return myItem; } } 

If you create an instance of this class, you change the type of the variable T with the real one:

 MyClass<SpecificItem > concreteClass = new MyClass<SpecificItem >(); 

And if you call myMethod on this instance, you must specify SpecificItem , because SpecificItem is the generic type for this instance.

(I'm not sure my post answers your question, please comment so that I can improve it)

+9
source

This is better than you code for the interface. For instance:

In myMethod:

 <T extends <? super Item>> void (T item); 

This tells the compiler that it accepts only the generic type T, which is an implementation / extension of the Item interface / class. This will make sure that this input matches the correct type. The compiler guarantees this.

In the main class:

 Item myItem = new SpecificItem(); 

The code above is best practice. Get used to it. But (I am discouraging this) you can also code this:

 SpecificItem myItem = new SpecificItem(); 

You can read the Java source code. For example, in the java.util.Collections class. In the sort (List) method, you can notice that Joshua Bloch is sure that this input is always in the correct format. To try, do the following:

 public class Class1 { public static void main(String[] args) { List<Class1> list = new ArrayList<Class1>(); Collections.sort(list); } } 

Above code will create a compilation error. To fix this compilation error, Class1 must implement the Comparable interface. This supports the List sorting prerequisite, which assumes that this input is a list of comparisons.

Oh, I almost forgot about your question. This is actually not bad code, as it works. I just want to tell you that there is a better way to do this.

+2
source

Perhaps you are looking for something like this:

 class C<? extends T> { public void myMethod(T myItem) { ... } } 
+1
source

The method call method looks strange. If you declared your general method as

 public <T> void myMethod(T item); 

the compiler knows that T is an abstract type, and you do not need to enter an input parameter into it. Just make sure T is not declared as a specific type in your code.

upd: look here: http://www.java2s.com/Tutorial/Java/0200__Generics/Usinggenericmethodstoprintarrayofdifferenttypes.htm

+1
source

Probably the best way would be to make SpecificItem a subclass of T or make T an interface and implement SpecificItem.

0
source

All Articles