实体MyObject
具有以下属性:
private String tblName;
private String colName;
private String dataType;
我有一个列表:List<MyObject>
。现在我需要将此List转换为单个String以进行调试,例如:
Object 1: (dataType=test, colName=test2, dataType=int), Object 2..."
这样做的最佳方式是什么?
答案 0 :(得分:1)
您可以覆盖toString
上的MyObject
方法,如下所示
public class MyObject
{
private String tblName;
private String colName;
private String dataType;
public String getTblName()
{
return tblName;
}
public void setTblName(String tblName)
{
this.tblName = tblName;
}
public String getColName()
{
return colName;
}
public void setColName(String colName)
{
this.colName = colName;
}
public String getDataType()
{
return dataType;
}
public void setDataType(String dataType)
{
this.dataType = dataType;
}
public String toString()
{
return String.format("(tblName=%s, colName=%s, dataType=%s)", tblName, colName, dataType);
}
}
对于ArrayList
,您需要迭代列表并构建结果
public static void main(String[] args)
{
ArrayList<MyObject> objectList = new ArrayList<MyObject>();
MyObject obj1 = new MyObject();
obj1.setColName("Col1");
obj1.setTblName("Tab1");
obj1.setDataType("data1");
MyObject obj2 = new MyObject();
obj2.setColName("Col1");
obj2.setTblName("Tab1");
obj2.setDataType("data1");
objectList.add(obj1);
objectList.add(obj2);
StringBuilder stringBuilder = new StringBuilder();
int count = 1;
for (MyObject myObject : objectList)
{
stringBuilder.append(String.format("Object %d %s ", count, myObject.toString()));
count++;
}
System.out.println(stringBuilder.toString());
}