vksd vksd - 4 months ago 21
Java Question

Generic methods to whom I can pass String parameter

I have a string-like class

myString
. To its methods, I would like to pass generic types T, where T can either be a string, or an object of
myString
. What I have done so far is put the methods of the String class that I use (such as
charAt(), size()
) into an interface
myInterface
, and written something like this:

class myString implements myInterface{
public <T extends myInterface> void mymethod(
T inputString){
}
}


What I want is that
inputString
can be either a String or a
myString
object.

However, I get an error that says
String is not a valid type for T
.

What I am doing wrong?

PS: This is my first question on Stack, so pl. bear with me.

Answer

You should use java.lang.CharSequence interface instead of MyInterface to define your own string class. And your method reference the generic type should be:

public <T extends CharSequence> void mymethod(T inputString) {
    ...
}

BTW, CharSequence does not have size() method, so you should use length() instead.

Refer to

Comments