我创建了一个链表类来创建一个简单的注册表,在这里我可以从列表中添加和删除学生。然而,我不知道如何创建我的toString方法链表,什么是最好的方式去做这个?提前感谢!
import java.util.*;
public class Registry {
LinkedList<Student> studentList
= new LinkedList<Student>();
//setting my type parameter
public Registry() {}
public void addStudent(Student aStudent) {}
public void deleteStudent(int studentID) {}
public String toString(){}
public String format() {}
}
LinkedList已经有一个继承自AbstractCollection的toString()方法。
toString
public String toString()
Returns a string representation of this collection. The string representation consists
of a list of the collection's elements in the order they are returned by its iterator,
enclosed in square brackets ("[]"). Adjacent elements are separated by the characters
", " (comma and space). Elements are converted to strings as by String.valueOf(Object).
Overrides:
toString in class Object
Returns:
a string representation of this collection
这不是你想要的吗? 目的似乎是列出存储在链表中的所有学生,而不是覆盖链表的toString()
。只要你的Student
类覆盖了它的toString()
方法,你就在你的路上了。打印链表将调用它的toString()
方法并给出您想要的结果。
示例类重写toString()
class MyClass
{
private int x;
private int y;
/* getters and setters */
@Override
public String toString()
{
return "MyClass [x=" + x + ", y=" + y + "]";
}
}
使用List<MyClass> myList = new LinkedList<MyClass>();
MyClass myClass = new MyClass();
myClass.setX(1);
myClass.setY(2);
myList.add(myClass);
System.out.println(myList);
打印
[MyClass [x=1, y=2]]
在注册表类中重写toString()
LinkedList将调用成员对象的toString()
来源 Returns a string representation of this collection. The string representation consists of a list of the collection's elements in the order they are returned by its iterator, enclosed in square brackets ("[]"). Adjacent elements are separated by the characters ", " (comma and space). Elements are converted to strings as by java.lang.String.valueOf(java.lang.Object).
- 你没有创建一个链表类——你创建了一个
LinkedList
对象。 -
你想要的是一个toString()方法为您的
Registry
类公共字符串toString() {boolean bracketAdded = false;StringBuffer = new StringBuffer();
for(Student student : studentList) { result.append(bracketAdded ? ", " : "["); result.append(student); bracketAdded = true; } result.append("]"); return result.toString();
}
现在剩下的就是为你的Student
类实现一个toString()
方法。
我会使用StringBuilder并循环遍历列表。
public String toString(){
StringBuilder sb = new StringBuilder();
for (Student s: students){
sb.append(s.toString()+",");
}
return sb.toString();
}
在你的Student类toString()方法中包含你想要的任何信息
编辑:我注意到在另一个响应中,链表上的toString()正在使用String.valueOf()。实际上,在大多数情况下我更喜欢这样,因为它会处理空值,当然,除非你想知道空值什么时候出现在这个列表中。
所以不是:
sb.append(s.toString()+",");
你可以使用:
sb.append(String.valueOf(s),"+");