我试图按学生姓氏升序对列表进行排序并显示列表,但我想删除返回null的[,]。有没有办法我看不到呢。

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class StudentTest  {

    public static void main(String args[]) {
        List<Student> list = new ArrayList<Student>();



       list.add(new Student(" Gracia", "50","\tCOP2250, COP3250, COP4250"));
       list.add(new Student(" Jones", "30", "\tCOP1210, COP3337, COP3530"));
       list.add(new Student(" Smith", "10", "\tCOP2250, COP3250, COP4250"));
       list.add(new Student(" Wilson", "20", "\tWNC1105, ENC3250, REL2210"));
       list.add(new Student(" Braga", "10", "\tENC1105, ENC3250, ISO4250"));
       list.add(new Student(" Adams", "20", "\tWNC1105, ENC3250, REL2210"));
       list.add(new Student(" Giron", "60","\tCOP1210, COP3337, COP3530"));
       list.add(new Student(" O'Neal", "45","\tENC1105, ENC3250, REL2210"));
       list.add(new Student(" Ervin", "40",  "\tENC1105, COP3250, ISO4250"));
       list.add(new Student(" Bourne", "70","\tCOP2250, ENC3250, COP3530"));


        System.out.println(list);
        Collections.sort(list);
        System.out.println(list);

    }
}

class Student implements Comparable<Student> {


    public Student(String name, String id, String course) {
        this.name = name;
        this.id = id;
        this.course = course;
    }

    public String getName() {

        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getCourse() {
        return course;
    }


    public Student(String course) {
        this.course = course;
    }

    private String name;
    private String id;
    private String course;



    @Override
    public int compareTo(Student student) {

        return name.compareTo(student.name);

    }


    @Override
    public String toString() {


       System.out.println("" + id + name + course );

        return "";

    }
}


输出如下:


10史密斯COP2250,COP3250,COP4250

20威尔逊WNC1105,ENC3250,REL2210

10 Braga ENC1105,ENC3250,ISO4250

20亚当斯WNC1105,ENC3250,REL2210

60吉伦COP1210,COP3337,COP3530

45奥尼尔ENC1105,ENC3250,REL2210

40 Ervin ENC1105,COP3250,ISO4250

70 Bourne COP2250,ENC3250,COP3530

[,,,,,,,,,,]


我为什么要得到这条线?


[,,,,,,,,,,]


谢谢你的帮助!

最佳答案

当您执行System.out.println(list);时,只需使用ArrayList.toString()方法的默认实现,该方法将返回列表中[]括号中的值,并用逗号和空格分隔。
您有两个选择:


自己遍历列表,并单独打印每个学生(只要它具有toString()方法实现即可。
或者,您可以对list.toString()中现在使用的String使用replaceAll()。


通常首选使用第一个选项,因为在常见情况下,"[" "]" ", "可以是列表元素内的有效字符,并且不能替换。
但是,在很小的情况下,如果您确定Student name, id or course中将没有这样的字符,则可以这样做。

09-13 06:39