Project
IntelliJ IDEA
Priority
Major
Type
Feature
Fix versions
No Fix versions
State
Open
Assignee
Alexey Kudravtsev
Subsystem
Editor. Intention Actions
Affected versions
No Affected versions
Fixed in build
No Fixed in build
  • Created by   Peter Lawrey
    6 years ago (31 Aug 2005 14:45)
  • Updated by   root
    2 years ago (17 Jan 2010 20:23)
  • Jira: IDEADEV-2334
    (history, comments)
 
IDEA-29993 As well as the intension "Cast to String" offer "Call toString()"
0
Issue is visible to: All Users
  The issue is visible to the selected user group only
I have been making more use of CharSequence in text processing to avoid unnecessary generating Strings.

A trivial example is.
public CharSequence cut(CharSequence str, int len) {
if (str.length <= len)
return;
StringBuilder ret = new StringBuilder(len);
ret.append(str.subSequence(0, len-3));
ret.append("...");
return ret;
}

This result can be used in a StringBuilder, or be passed to a method which requires a String.
e.g.
public void setDescription(String description) { ... }

setDescription(cut(longDescription, MAX_LENGTH));

One of the options is to cast to String.

setDescription((String) cut(longDescription, MAX_LENGTH));

This may work some of the time, but a better, possiblily more reliable suggestion is call toString()

setDescription(cut(longDescription, MAX_LENGTH).toString());

I believe calling toString() may be a better way convert in a wide range of situations.
Comments (2)
 
History
 
Linked Issues (?)
 
Bas Leijdekkers
  Bas Leijdekkers
31 Aug 2005 17:03
6 years ago
but better watch out for NullPointerExceptions.
Peter Lawrey
  Peter Lawrey
31 Aug 2005 20:25
6 years ago
If you have fail fast coding and you want a NullPointerException as early as possible. .e.g as close to the caus eof the null value as possible.
In this case, a NullPointerException will be thrown earlier (e.g. str.length())

In cases where you want to preserve null values, you can keep the option to cast instead of calling toString().