I know it might have no sense at all, but it's just my experiment. There are 3 types (as I know) that supports method substring()
. I wan't to make a generic method like this:
public static <T extends String & StringBuilder & StringBuffer> T substr3(T str) {
if (str.length() > 3) {
return (T) str.substring(0, 3);
}
return str;
}
It won't compile like this, because you can use as many interfaces as you need, but only one Class as bounded type. This method should work fine for this 3 types: String
, StringBuilder
, StringBuffer
but the questions is: how to set this 3 types as bound types ?
Whenever you want to restrict the type parameter to subtypes of a particular class you can use the bounded type parameter. If you just specify a type (class) as bounded parameter, only sub types of that particular class are accepted by the current generic class. These are known as bounded-types in generics in Java.
There may be times when you want to restrict the types that can be used as type arguments in a parameterized type. For example, a method that operates on numbers might only want to accept instances of Number or its subclasses. This is what bounded type parameters are for.
A type parameter can have multiple bounds.
Why not simply extend CharSequence
?
public static <T extends CharSequence> T substr3(T str) {
if (str.length() > 3) {
return (T) str.subSequence(0, 3);
}
return str;
}
Note
CharSequence
doesn't declare any substring
method, but subSequence
should provide the identical functionality.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With