I did some search on this and all I found was that BigDecimal has a constructor that we can pass String to it and it will convert it for us.
But in my case what I have is a java.lang.CharSequence and what I need it to be is BigDecimal
What is the correct way to do this conversion?
new BigDecimal(myCharSeq.toString())
I'd use CharSequence.toString together with the constructor you mentioned. toString documentation:
Returns a string containing the characters in this sequence in the
same order as this sequence. The length of the string will be the
length of this sequence.
This turns into:
new BigDecimal(mySequence.toString());
Call toString() on the CharSequence and build BigDecimal out of it. Javadoc is your friend.
Use the .toString method of CharSequence Interface
I have corrected my self actually CharSequence is an interface which has its own toString() method.
toString(); -- Returns a string representation of the object.
Refer the ofiicial docs of CharSequnce Interface http://docs.oracle.com/javase/6/docs/api/java/lang/CharSequence.html
BigDecimal bigDecimal = new BigDecimal(charSeq.toString());
Like this
StringBuilder sb = new StringBuilder(charSequence.length());
sb.append(charSequence);
BigDecimal bigDecimal = new BigDecimal(sb.toString());
This protects you in case there's a problem with the charSequence concrete class implementation of toString(). CharSequence is an interface that could be backed by a user written concrete class.
Related
Here's the situation, I have an Object in a Map which I explicitly know to contain an instance of Long and I need to turn that value into a string but keep getting incompatible type errors. Here's what my code looks like:
Map<String, Object> map = ...;
Object obj = new Long(31415L);
String str = Long.valueOf((long)map.get("id")); //Problem line
This gives:
Inconvertible types.
Found : java.lang.Object
Required: long
Any suggestions as to how to get around this?
You can just do
String str = map.get("id").toString();
Use, for instance:
String.valueOf(map.get("id"))
The problem is that you try and cast an object to a primitive type. That cannot work.
But since the values of your map will be Longs anyway (collections cannot contain primitive types, save for specialized implementations such as found in GNU Trove), look at #BheshGurung's answer...
You can use the toString function;
public String toString() {
return String.valueOf(map.get("id"))
}
String str = map.get("id").toString();
You have 2 issues here:
You created a *L*ong, not a *l*ong. Therefore you need to cast back to a *L*ong, not a *l*ong.
In order to get the String representation of a *L*ong you must call toString() on it.
Use this:
String str = ((Long)map.get("id")).toString();
The following is my java code snippet:
static String sortChars(String s) {
char[] chars = s.toCharArray();
Arrays.sort(chars);
return chars.toString();
}
I invoke above function by using:
String result = sortChars(s);
But the result does not meet my expectation:for example,the s="are", the result="aer". However, when I use:
return new String(chars)
It works.
Could somebody tell me the reason of it. Thanks
Since char[] class does not override the default Object's toString() implementation, it does not return a string composed by the characters in the char array, but the char[] class name + hash code. For example: arr[C#19821f.
toString() returns a string representation of the Object. You can look at it as a description of the object.
new String(chars) will give you a String with the content of the char array.
Use toString() if you want to represent an Object to the user or in a log, use new String() if you want to get a String object that is the same as the content of your array
Note that, among the constructors for a Java String is one that accepts a character array. That converts the character array into a string as you would expect, and it is the correct choice for what you are doing.
I'm trying to figure out how java classes work.
When I create a StringBuilder:
StringBuilder testString = new StringBuilder("Hello World!);
If I want to, say, get the value that testSting holds a reference to, I can simply call it like: System.out.println(testString);
This is cool behavior, but I'm unsure how to replicate it in classes that I make.
For instance, if I were to try and re-implement my own version of StringBuilder, the approach I would take (as a beginner), would be this:
class MyBuilder {
char[] string;
public MyBuilder(String s) {
string = new char[s.length()];
string = s.toCharArray();
}
So, to make the string an array I had to store it in a data field of the class. But then, to access this in my code, I can't print it by simply calling the variable name. I would have to use .property syntax. Thus, to duplicate the above example, I would have to type System.out.println(testString.value); Which isn't nearly as pretty.
How do you make a class such that it behaves like String or StringBuilder and returns its value without manually accessing the data fields?
Implement a toString method.
toString is a method on Object, so every java object inherits one. The default implementation that you inherit is only useful for getting the class type, and for distinguishing one object from another; the format is: ClassName#HashCode. There are no details unique to your implementation.
In your own classes, to get the description that you want you'll need to override the toString method, so that in contexts where a String is expected, e.g. when you call System.out.println(myObject.toString());, your own format is used.
It's often a good idea to do this, for a more readable description of your object. You can always call super.toString to include the output from the default - ClassName#HashCode - in your own output.
You can override Object.toString() in your object MyBuilder. System.out.println calls on this method for every object used. For example here, you could use:
#Override
public String toString() {
return Arrays.toString(string);
}
Overwrite the toString-Method
private String value;
public MyClass(String value) {
this.value = value;
}
public String toString() {
return value;
}
I'd like to ask that, how can i use ArrayList to store a toString(). I've got a class, with a toString at the end, and i have to store the toString from the class into the ArrayList.
Like this : Music name , author , release year , currently playing
String , String , int , boolean
hoping you have properly formatted text in your specific class's toString() method,
use
List<String> listDesired = new ArrayList<String>( 10 );
listDesired.add( myMusicDataClassInstance.toString() );
Question is unclear, but if your objects already have toString() method defined you don't need to store them separately in array list. Just add the objects to arrayList and do Collections.toString(yourList);
You can use the "" + x trick so as to avoid NullPointerException in case an x is null:
public List<String> musicToString(List<Music> musicList) {
final List<String> strings = new ArrayList<String>();
for (Music m : musicList) strings.add("" + m);
return strings;
}
This works because the concatenation operator + implicitly calls String.valueOf on all reference-typed operands.
You can also write String.valueOf explicitly, if that is your aesthetic preference. It also has the marginal benefit of definitely not instantiating a StringBuilder (although there's a good chance the compiler will avoid that anyway since it can see the empty string literal).
You should override the toString() for that class and in toString() method define the business logic that will convert that string into ArrayList object.
List<String> listDesired = new ArrayList<String>( 10 );
How can I convert a Java CharSequence to a String?
By invoking its toString() method.
Returns a string containing the characters in this sequence in the same order as this sequence. The length of the string will be the length of this sequence.
There is a subtle issue here that is a bit of a gotcha.
The toString() method has a base implementation in Object. CharSequence is an interface; and although the toString() method appears as part of that interface, there is nothing at compile-time that will force you to override it and honor the additional constraints that the CharSequence toString() method's javadoc puts on the toString() method; ie that it should return a string containing the characters in the order returned by charAt().
Your IDE won't even help you out by reminding that you that you probably should override toString(). For example, in intellij, this is what you'll see if you create a new CharSequence implementation: http://puu.sh/2w1RJ. Note the absence of toString().
If you rely on toString() on an arbitrary CharSequence, it should work provided the CharSequence implementer did their job properly. But if you want to avoid any uncertainty altogether, you should use a StringBuilder and append(), like so:
final StringBuilder sb = new StringBuilder(charSequence.length());
sb.append(charSequence);
return sb.toString();
You can directly use String.valueOf()
String.valueOf(charSequence)
Though this is same as toString() it does a null check on the charSequence before actually calling toString.
This is useful when a method can return either a charSequence or null value.
The Safest Way
String string = String.valueOf(charSequence);
Let's Dive Deep
There are 3 common ways that we can try to convert a CharSequence to String:
Type Casting: String string = (String) charSequence;
Calling toString(): String string = charSequence.toString();
String.valueOf() Method: String string = String.valueOf(charSequence);
And if we run these where CharSequence charSequence = "a simple string"; then all 3 of them will produce the expected result.
The problem happens when we are not sure about the nature of the CharSequence. In fact, CharSequence is an interface that several other classes implement, like- String, CharBuffer, StringBuffer, etc. So, converting a String to a CharSequence is a straightforward assignment operation, no casting or anything is required. But, for the opposite, Upcasting, it is not true.
If we are sure that the CharSequence is actually an object of String, only then we can use option 1- Type Casting. Otherwise, we will get a ClassCastException. Option 2 and 3 are safe in this case.
On the other side, if the CharSequence is null then option 2, calling toString(), will give a NullPointerException.
Now internally, String.valueOf() method calls the toString() method after doing a null check. So, it is the safest way. JavaDoc:
if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.
Please be aware: If CharSequence is null then String.valueOf() method return the string- "null", not null value.
If you want to convert an array of CharSequence,
You can simply do this and can also be store it in a String[] variable.
CharSequence[] textMsgs = (CharSequence[])sbm.getNotification().extras.get(Notification.EXTRA_TEXT_LINES);
if (textMsgs != null) {
for (CharSequence msg : textMsgs) {
Log.e("Msg", msg.toString());
}
}
Also you can une Stringbuilder.
new StringBuilder(charSequence).toString();