将List <String>打印到logcat

joh*_*p34 12 java debugging android logcat android-logcat

我可以看到log.d需要

Log.d(String TAG, String). 
Run Code Online (Sandbox Code Playgroud)

如何在android调试logcat中打印一个List String而不仅仅是一个String?

Ham*_*atu 32

使用toString()方法,该方法可用于大多数常见数据结构:

Log.d("list", list.toString());
Run Code Online (Sandbox Code Playgroud)

如果您声明使用Java定义的List/ Collection使用Generic类型,则上面的语句将为您提供预期的结果.如String,Integer,Long等原因,它们都有实现toString()方法.

Custome通用类型:

但是,如果您声明List使用自己的自定义类型,那么只需调用就无法获得正确的输出list.toString().您需要toString()为自定义类型实现方法以获得预期的输出.

例如:

您有一个名为Dog如下的模型类

public class Dog{
   String breed;
   int ageC
   String color; 
}
Run Code Online (Sandbox Code Playgroud)

您声明了一个List使用Dog类型

List<Dog> dogList = new ArrayList<Dog>();
Run Code Online (Sandbox Code Playgroud)

现在,如果要LogCat正确打印此List,则需要toString()Dog类中实现方法.

public class Dog{
   String breed;
   int age
   String color;

   String toString(){
       return "Breed : " + breed + "\nAge : " + age + "\nColor : " + color;
   } 
}
Run Code Online (Sandbox Code Playgroud)

现在,如果你打电话,你会得到正确的结果list.toString().