Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - generic method with bounded types for 3 similar types: String, StringBuilder, StringBuffer

Tags:

java

generics

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 ?

like image 833
RichardK Avatar asked Oct 17 '14 13:10

RichardK


People also ask

What are bounded types with generics in Java?

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.

What is bounded type in generics?

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.

Is it possible to declared a multiple bounded type parameter?

A type parameter can have multiple bounds.


1 Answers

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.

like image 136
Mena Avatar answered Nov 15 '22 04:11

Mena