我创建了一个链接列表来创建一个简单的注册表,我可以在列表中添加和删除学生。但是我不知道如何为链表创建我的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() {}
}
答案 0 :(得分:3)
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
这不是你想要的吗?
答案 1 :(得分:1)
目的似乎是列出存储在链接列表中的所有学生,而不是覆盖链接列表的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]]
答案 2 :(得分:0)
我会使用StringBuilder并在列表中循环。
public String toString(){
StringBuilder sb = new StringBuilder();
for (Student s: students){
sb.append(s.toString()+",");
}
return sb.toString();
}
在Student class toString()方法中包含您想要的任何信息。
编辑:我注意到其他一个响应中链表上的toString()使用的是String.valueOf()。在大多数情况下,我实际上更喜欢它,因为它会处理空值,除非你当然想知道null何时在这个列表中结束。
所以而不是:
sb.append(s.toString()+",");
您可以使用:
sb.append(String.valueOf(s),"+");
答案 3 :(得分:0)
覆盖Registry类中的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).
答案 4 :(得分:0)
LinkedList
对象。您想要的是Registry
类
public String toString(){ boolean bracketAdded = false; StringBuffer result = new StringBuffer();
for(Student student : studentList) {
result.append(bracketAdded ? ", " : "[");
result.append(student);
bracketAdded = true;
}
result.append("]");
return result.toString();
}
现在剩下的就是为toString()
课程实施Student
方法。