Just use
return ma.toString();
instead of
return ma;
ma.toString() returns the string representation for your StringBuilder.
See StringBuilder#toString() for details
As Valeri Atamaniouk suggested in comments, you should also return something in the catch block, otherwise you will get a compiler error for missing return statement, so editing
} catch (Exception e) {
Log.e("ERR",e.getMessage());
}
to
} catch (Exception e) {
Log.e("ERR",e.getMessage());
return null; //or maybe return another string
}
Would be a good idea.
EDIT
As Esailija suggested, we have three anti-patterns in this code
} catch (Exception e) { //You should catch the specific exception
Log.e("ERR",e.getMessage()); //Don't log the exception, throw it and let the caller handle it
return null; //Don't return null if it is unnecessary
}
So i think it is better to do something like that:
private static String getUrlSource(String url) throws MalformedURLException, IOException {
URL localUrl = null;
localUrl = new URL(url);
URLConnection conn = localUrl.openConnection();
BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line = "";
String html;
StringBuilder ma = new StringBuilder();
while ((line = reader.readLine()) != null) {
ma.append(line);
}
return ma.toString();
}
And then, when you call it:
try {
String urlSource = getUrlSource("http://www.google.com");
//process your url source
} catch (MalformedURLException ex) {
//your url is wrong, do some stuff here
} catch (IOException ex) {
//I/O operations were interrupted, do some stuff here
}
Check these links for further details about Java Anti-Patterns:
- Java Anti-Patterns
- Programming Anti-Patterns
- An Introduction to Antipatterns in Java Applications
Just use
return ma.toString();
instead of
return ma;
ma.toString() returns the string representation for your StringBuilder.
See StringBuilder#toString() for details
As Valeri Atamaniouk suggested in comments, you should also return something in the catch block, otherwise you will get a compiler error for missing return statement, so editing
} catch (Exception e) {
Log.e("ERR",e.getMessage());
}
to
} catch (Exception e) {
Log.e("ERR",e.getMessage());
return null; //or maybe return another string
}
Would be a good idea.
EDIT
As Esailija suggested, we have three anti-patterns in this code
} catch (Exception e) { //You should catch the specific exception
Log.e("ERR",e.getMessage()); //Don't log the exception, throw it and let the caller handle it
return null; //Don't return null if it is unnecessary
}
So i think it is better to do something like that:
private static String getUrlSource(String url) throws MalformedURLException, IOException {
URL localUrl = null;
localUrl = new URL(url);
URLConnection conn = localUrl.openConnection();
BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line = "";
String html;
StringBuilder ma = new StringBuilder();
while ((line = reader.readLine()) != null) {
ma.append(line);
}
return ma.toString();
}
And then, when you call it:
try {
String urlSource = getUrlSource("http://www.google.com");
//process your url source
} catch (MalformedURLException ex) {
//your url is wrong, do some stuff here
} catch (IOException ex) {
//I/O operations were interrupted, do some stuff here
}
Check these links for further details about Java Anti-Patterns:
- Java Anti-Patterns
- Programming Anti-Patterns
- An Introduction to Antipatterns in Java Applications
I have same problem while converting StringBuilder to String, and i use above point but that's not give correct solution. using above code output comes like this
String out=ma.toString();
// out=[Ljava.lang.String;@41e633e0
After that i find out correct solution.Think is create a new String instant inserted of StringBuilder like this..
String out=new String(ma);
In Java, you can't define implicit conversions between types, beyond what's in the specification - so you can't convert from StringBuilder to String anyway; you have to call toString().
In C# there could be an implicit user-defined conversion between StringBuilder and String (defined in either StringBuilder or String), but there isn't - so you still have to call ToString().
In both cases you will get a compile-time error if you don't call the relevant method.
In C#, you need to use string foobar = sb.ToString(); or you will get an error:
Cannot implicitly convert type 'System.Text.StringBuilder' to 'string'.
scala - What's the correct way to convert from StringBuilder to String? - Stack Overflow
java - String cannot be converted to StringBuffer - Stack Overflow
c# - some problems with converting from StringBuilder to string - Stack Overflow
java - How can a StringBuilder best be converted to a String[]? - Stack Overflow
The toString implementation currently just redirects to the result method anyway, so those two methods will behave in the same way. However, they express slightly different intent:
toStringrequests a textual representation ofStringBuilders current state that is "concise but informative (and) that is easy for a person to read". So, theoretically, the (vague) specification of this method does not forbid abbreviating the result, or enhancing conciseness and readability in any other way.resultrequests the actual constructed string. No different readings seem possible here.
Therefore, if you want to obtain the resulting string, use result to express your intent as clearly as possible.
In this way, the reader of your code won't have to wonder whether StringBuilder.toString might shorten something for the sake of "conciseness" when the string gets over 9000 kB long, or something like that.
The mkString is for something else entirely, it's mostly used for interspersing separators, as in "hello".mkString(",") == "h,e,l,l,o".
Some further links:
- The paragraph with "hashcode in hexadecimal" describes the default. It is just documentation inherited from
AnyRef, because the creator ofStringBuilderdidn't bother to provide more detailed documentation. - If you look into code, you'll see that
toStringis actually just delegating toresult. - The documentation of
StringBuilderalso mentionsresult()in the introductory overview paragraph.
Just use result().
TL;DR; use result as stated in the docs.
toString MUST never be called in anything at all for another purpose other than a quick debug.
mkString is inherited from collections hierarchy and it will basically create another StringBuilder so is very inefficient.
1) Create StringBuffer object and pass it to addFilter().
2) Convert StringBuffer object return by addFilter() into String by toString().
keyword = addFilter(new StringBuffer(keyword)).toString();
String is final and immutable too.
Hence, this class cannot be extended or inherited by any other class. So, there is no IS-A Relationship between these two classes. String can never be converted or referenced to any other Class except java.lang.Object directly.
But StringBuffer provides a Constructor through which you can convert a String into a StringBuffer Object.
public java.lang.StringBuffer(java.lang.String); //pass string as an argument. StringBuffer object will you get.
In your case, try this code:
addFilter(new StringBuffer(keyword)).toString();
So you're just trying to split on tab? How about:
return names.toString().split(TAB);
Note that split takes a regular expression pattern - so don't expect split(".") to split just on dots, for example :)
To dynamically grow array, use ArrayList<String>, you can even convert the result to String[] if that's what your API requires.
ArrayList<String> namesList = new ArrayList<String>( );
while (-1 != end) {
end = names.indexOf(TAB, start);
namesList.add( names.substring(start, end) );
start = ++end; // The next name is after the TAB
}
return namesList.toArray( new String[ namesList.size( ) ] );
That said, for your purposes use split as suggested by others