Print a List<String> to logcat
Make use of toString() method which is available for most common data structures:
Log.d("list", list.toString());
Above statement will give you the expected result if you declare your List
/Collection
using Generic type defined in Java. Such as String, Integer, Long etc. Cause, they all have implemented toString()
method.
Custome Generic Type:
But if you declare the List
using your own custom type then you will not get proper output by just calling list.toString()
. You need to implement toString()
method for your custom type to get expected output.
For example:
You have a model class named Dog
as below
public class Dog{
String breed;
int ageC
String color;
}
You declared a List
using Dog
type
List<Dog> dogList = new ArrayList<Dog>();
Now, if you want to print this List in LogCat
properly then you need to implement toString()
method in Dog
class.
public class Dog{
String breed;
int age
String color;
String toString(){
return "Breed : " + breed + "\nAge : " + age + "\nColor : " + color;
}
}
Now, you will get proper result if you call list.toString()
.