Generic trim function in java? - java

i have a requirement, where i need to develop a single method which accepts any type of paramter(String or Integer etc) and applies trim() to remove leading and trialing spaces. please help me how to write generic method to achieve this?
Thanks!

Java has strictly defined types, it's not PHP or Javascript. Integer does not have spaces. Simply use trim() method of String object. If your 'integer' is actually a string, do (String.valueOf(x)).trim()

It does not make a lot of sense, but here it goes:
public String trim(Object o) {
if (o != null) {
return o.toString().trim();
}
return null;
}

if an integer is like 12345---. --- indicates 3 spaces. how can i remove? do i need to convert it to string before trimming?
If an 'integer' has trailing spaces, it is already the string representation of the integer, not the integer itself. Therefore:
String i = "12345 ";
String trimmed = i.trim();
By contrast, the following is simply not legal
int i = "12345 "; // compilation error
and a string representation of an integer produced like this:
String i = String.valueOf(12345);
will not have leading or trailing whitespace.

In java, all objects have .toString() method which returns string representation of that object.
You can then call .trim() method on that string, so your function may look like this:
public static String trimAny(Object o) {
return o.toString().trim();
}

Related

Differrence Between strValue.toString() & strValue+"" & ""+strValue

Converting the value to String in java; There are multiple ways of doing it.
Just wanted to know what's the difference between each other in the following ways.
strValue.toString()
strValue+""
""+strValue
It depends on java version. Java 7 would act a bit smarter using StringBuilder + append().
Generally, you do not want unnecessary allocations. Use first one.
strValue.toString()
will return itself, because the toString() implementation of String (I'm guessing strValue is indeed of type String) returns this.
strValue+""
""+strValue
Will result in the same value (strValue) but won't invoke the toString() method
All Strings contain the same value, try it out:
String strValue = "Hello world"; // not null
String a = strValue.toString();
String b = strValue+"";
String c = ""+strValue;
Measuring its length give all the result 11, because adding an empty String to another one equals the original String itself:
System.out.println(a.length());
...
Try the equality between these Strings:
System.out.println(a.equals(b));
System.out.println(b.equals(c));
System.out.println(c.equals(a));
They are all true, because these Strings have the same value to be compared. All it in the case the strValue is not null.
One major difference is how null is handled.
If strValue is null, strValue.toString() will throw a NullPointerException, while the other two options will return the String "null".
Other differences may be observed if strValue is of a boxed numeric type, and you try to concatenate other numeric variables to it.
For example :
If
Integer a = 5;
Integer strValue = 6;
Then
a+strValue+""
would return
"11"
while
a+""+strValue
or
""+a+strValue
would return
"56"

toString in the java code

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.

How to convert CharSequence to String?

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();

Removing Backing Array From Strings

I want to get the first 4 characters of a string to compare with another string. However, when I do something like
String shortString;
shortString = longString.subString(0,3);
It takes along longString's backing array and makes it impossible to compare easily.
I've also tried converting longString into a character array and inserting each character but I always seem to end up with long string. The Android Development documents say to use the String constructor to remove the backing array but it doesn't seem to work for me either.
String shortString = new String(longString.subString(0,3));
Any suggestions would be appreciated!
First, it's string.substring() not .subString().
Second, what do you mean "impossible to compare easily"? You can compare strings with .equals() easily.
public static void main(String[] args) {
String longString = "abcdefghijklmn";
String shortString = longString.substring(0, 3);
System.out.println(shortString.equals(longString));
}
this code prints false, as it should.
Update:
If you call .substring() so that it produces string of the same length as original string (e.g. "abc".substring(0,2)) than it will return reference to the same string. So, .equals() in this case will return true.
How would you want to compare? There's built in method for simple comparison:
longString.subString(0, 3).compareTo(anotherString);
Alternatively, since String is a CharSequence, something like:
for (int i=0; i<4; i++){
if (anotherString.charAt(i) != shortString.charAt(i)) return false;
}
would work as well.
Finally, every String is constructed in backing Array, there's no way to deny it, and longString.subString(0,3) would always (except index out of bound) return a String with a 4-element Char Array.
In the event that you actually need to get rid of the backing array the following will work:
String newString = StringBuilder(oldString).toString();
This might be necessary, for example, if you are parsing strings and creating substrings and you might need to do this:
String newString = StringBuilder(oldString.substring(start,end).toString();
This creates a truly new string with a zero offset and independent backing array. Otherwise, you maintain the same backing array which, in rare cases might cause a problem for the heap because it can never be garbage collected.

Java return arrays

I'm having trouble returning arrays from a custom method. It compiles fine but I get back:
[Ljava.lang.String;#20cf2c80
Press any key to continue . . .
I use:
System.out.println(getItem(1));
code:
public static String[] getItem(int e) {
String[] stats = new String[7];
String name = "Null";
String desc = "None";
String typeOf = "0";
String attackAdd = "0";
String defenseAdd = "0";
String canSell = "true";
String canEat = "false";
String earnedCoins = "0";
if (e == 1) {
name = "Pickaxe";
desc = "Can be used to mine with.";
typeOf = "2";
}
return new String[] { name, desc, typeOf};
}
Help? :\
The toString() method of an array object actually doesn't go through and produce a string representation of the contents of the array, which is what I think you wanted to do. For that you'll need Arrays.toString().
System.out.println(Arrays.toString(getItem(1)));
The notation [Ljava.lang.String is Java code for a String array - in general, the default string representation of an array is [L followed by the type of the array's elements. Then you get a semicolon and the memory address (or some sort of locally unique ID) of the array.
That's not an error. The JVM simply prints the address of the array since it doesn't print its content. Try this and see what happens now?
System.out.println(getItem(1)[0]);
On Object.toString()
The reason why you're getting such string is because arrays simply inherit and not #Override the Object.toString() method.
The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character #, and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:
getClass().getName() + '#' + Integer.toHexString(hashCode())
To return a String representation of an array that lists its elements, you can use e.g. Arrays.toString, and for "multidimensional" arrays Arrays.deepToString
Related questions
toString() in Java
Simplest way to print an array in Java
On deepEquals and deepToString for "multidimensional" arrays:
Java Arrays.equals() returns false for two dimensional arrays.
On defining your own type
It needs to be said that your usage of String[] is not the best design choice.
Things would be so much better had you defined your own class BasicItem supported by various enum, with as many final fields as is practical to enforce immutability; perhaps something like this:
public enum ItemType {
KNIFE, SWORD, AXE;
}
public enum Attribute {
SELLABLE, EDIBLE;
}
public class BasicItem {
final String name;
final String desc;
final ItemType type;
final int attackAdd;
final int defenseAdd;
final Set<Attribute> attributes;
//...
}
You should really take advantage all the benefits of good object-oriented design.
See also
Effective Java 2nd Edition
Item 50: Avoid strings where other types are more appropriate
Item 25: Prefer lists to arrays
Item 30: Use enums instead of int constants
Item 32: Use EnumSet instead of bit fields
Item 15: Minimize mutability
Java Tutorials/Enums
Java Tutorials/Object Oriented Programming Concepts

Categories