简体   繁体   中英

Generics methods in Java

My question is: is it possible to make one generic method where I can use 2 different types? Eg an Integer and a String.

There is no practical use for this, but I'd just like to know if it's possible. And if it is, how? :)

You dont need to use generics for this. You can overload the methods. For example

public void method(Integer i){}

public void method(String s){}

If you call method with an integer then it will call the first method. If you call it with a string it will call the second method.

Presumably you mean two different types of parameter?

You could use one method for the String param, and another than takes the integer and passes it on to the String version.

The example types are not good one as the are final. This mean that you can not use them to limit the generic parameter as nothing can inherit from them.

So for that types the answer is No.

But what we can do with Java is:

You can create a method that accept Object type.

 public <T> void doStaff(T obj) {

 }

You can create a method that is limited to CharSequence as String is final

 public <T extends CharSequence> void doStaff(T str){ 

 } 

You can create a method that is litmited to more the one interface

public <T extends CharSequence & Comparable<T>> void doStaf(T interf) {

}

But even with so many possibilities we can not create a generic parameter that is valid for Two unrelated types. This would not have sense. As main task of generic type is to provide type safety. And in generally when we use them we should operate with interfaces not classes.

If you want your method to accept Integer and String, try below approach:

  public class Test {
public static void main(String[] a)  {
    method(new String(),new Integer("2"));
}
public static <T extends String, U extends Integer> void  method(T t, U u){

}
}

EDIT:

if you want your method to take a single parameter that takes either a String or Integer

try this :

public static <T extends Comparable<T>> void  method(T t){

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM