2015-11-03 67 views
0

我的問題是如何在我的logcat中打印arraylist內容的值?每個數組都有兩個字符串..我必須先將它更改爲數組嗎?如何在logcat中打印arraylist內容的值?

以下是我的高中班:

  public class SCHOOL { 

private String schoolid; 
private String schoolname; 
private List<STUDENT> students = new ArrayList<>(); 

// getters and setters for schoolid, schoolname 

public String getSchoolid() { 
    return schoolid; 
} 
public void setSchoolid(String schoolid) { 
    this.schoolid = schoolid; 
} 

public String getSchoolname() { 
    return schoolname; 
} 
public void setSchoolname(String schoolname) { 
    this.schoolname = schoolname; 
} 


public void setStudents(List<STUDENT> students) { 
    this.students = students; 
} 


public List<STUDENT> getStudents() {return this.students;} 


public void addStudent(String names, String age) { 
    STUDENT student = new STUDENT(); 
    student.setNames(names); 
    student.setAge(age); 
    students.add(student); 
    } 

以下是我的學生類: 公共類學生{

 private String names; 
     private String age; 

     public String getNames() { 
      return names; 
     } 

     public void setNames(String names) { 
      this.names = names; 
     } 

     public String getAge() { 
      return age; 
     } 

     public void setAge(String age) { 
      this.age = age; 
    } 
    } 

以下是我的主要活動:

... 

    SCHOOL school = new SCHOOL(); 

    school.addStudent("kent", "43"); 
    school.addStudent("Winnie", "42"); 
    school.addStudent("Dennis", "41"); 

    List<STUDENT> studentsList = school.getStudents(); 
    Log.d(tag, String.valueOf(studentsList)); 
    ... 

結果如下:

Tag Activity: [[email protected],  
        [email protected], 
        [email protected]] 

回答

1

你可以寫一個輸出方法定製輸出,如:

public String outputStudents(List<STUDENT> studentsList) { 
     StringBuilder sb = new StringBuilder(); 
     foreach (STUDENT student: studentLIst) { 
       sb.append(student.names); 
       sb.append(","); 
       sb.append(student.age); 
       sb.append(";"); 
     } 
     return sb; 
    } 

並使用下面的代碼來調用這個函數:

List<STUDENT> studentsList = school.getStudents(); 
Log.d(tag, outputStudents(studentsList)); 
5

替代方法toString()STUDENT。例如:

public class STUDENT { 

     String names; 
     String age; 

     @Override 
     public String toString() { 
      return "STUDENT{" + 
        "names='" + names + '\'' + 
        ", age='" + age + '\'' + 
        '}'; 
     } 
    } 
+0

感謝您的幫助亞瑟。 – Spidey

+1

@Spidey它可以幫助你接受答案(http://stackoverflow.com/help/accepted-answer)。 – yasd