3

The Scanner class has a constructor taking a String.

Scanner s = new Scanner( myString ) ;

How to feed a CharSequence object to a new Scanner? I could first generate a String from the CharSequence, but that is inefficient and rather silly.

Scanner s = new Scanner( myCharSequence.toString() ) ;  // Workaround, but seems needlessly inefficient to instantiate a `String`. 

I looking for a way to access the CharSequence directly from the Scanner. Something like this:

Scanner s = new Scanner( myCharSequence ) ;  // Use `CharSequence` directly.

The Scanner class also takes a Readable in a constructor. Can a CharSequence be presented as a Readable? Or is there some other workaround?

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154

1 Answers1

3

Given that the constructors only accept String and not the more generic CharSequence, you...can't. Not unless you invoke toString on the CharSequence, anyway, which would get you a String back, which would satisfy the constructor's requirements.

So, the workaround calling CharSequence::toString as seen in the Question is indeed the way to go:

new Scanner( myCharSequence.toString() ) 
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Makoto
  • 104,088
  • 27
  • 192
  • 230
  • Okay. :-( After reading your Answer, I edited to ask if a `CharSequence` might be presented as a `Readable` to satisfy another `Scanner` constructor. – Basil Bourque May 21 '18 at 00:24
  • [Javadoc says, "Nope"](https://docs.oracle.com/javase/10/docs/api/java/lang/Readable.html), since `Readable` not only doesn't give you back anything that'd represent a `CharSequence`, but it doesn't seem like it'd *really* be what you want, since `Readable` appears to deal with other stream-like entities. – Makoto May 21 '18 at 00:26