Java is a generic method with limited types for 3 similar types: String, StringBuilder, StringBuffer

I know this may not make any sense, but this is just my experiment. There are 3 types (as I know) that support the subString () method. I will not do the general method as follows:

public static <T extends String & StringBuilder & StringBuffer> T substr3(T str) { if (str.length() > 3) { return (T) str.substring(0, 3); } return str; } 

It will not compile this way because you can use as many interfaces as you need, but only one class as a limited type. This method should work fine for these three types: String, StringBuilder, StringBuffer, but there are questions: how to set these 3 types as limited types?

+5
source share
2 answers

Why not just 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 does not declare any substring method, but subSequence should provide identical functionality.

+12
source

One solution was also mentioned here:

 public static <T extends String, StringBuffer, StringBuilder> T substr3( T str) { if (str.length() > 3) { return (T) str.substring(0, 3); } return str; } 

instead of &.

-1
source

Source: https://habr.com/ru/post/1204924/


All Articles