Reputation: 35
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
Upvotes: 0
Views: 613
Reputation: 200148
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).
Upvotes: 1
Reputation: 9307
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)
;
Upvotes: 1
Reputation: 6657
You should override the toString()
for that class and in toString()
method define the business logic that will convert that string into ArrayList
object.
Upvotes: 0
Reputation: 23992
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() );
Upvotes: 2