我试图创建一个带有字符串和整数的(2)2d数组,以便以后能够在代码中对它们进行排序。这是我的代码到目前为止,我在尝试编译时不断出错,我不知道该怎么做:
public class SchoolBus {
public static void main(String[] args) {
Student[][] students = new Student[6][3];
students[0][0] = "Mabel";
students[0][1] = new int[1];
students[0][2] = new Integer(2);
students[1][0] = "Dipper";
students[1][1] = new Integer(1);
students[1][2] = new Integer(4);
students[2][0] = "Sam";
students[2][1] = new Integer(1);
students[2][2] = new Integer(7);
students[3][0] = "Ian";
students[3][1] = new Integer(2);
students[3][2] = new Integer(3);
students[4][0] = "Jordan";
students[4][1] = new Integer(2);
students[4][2] = new Integer(6);
students[5][0] = "Steven";
students[5][1] = new Integer(2);
students[5][2] = new Integer(9);
System.out.println(student);
}
}
答案 0 :(得分:0)
对于其他数据结构,请考虑使用例如List之类的Collection。集合允许您轻松排序。
以下是一个例子:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
public final class SchoolBus {
private SchoolBus() {
}
public static void main(final String[] args) {
final List<Student> students = new ArrayList<>();
students.add(new Student("Mabel", 1, 2));
students.add(new Student("Dipper", 1, 4));
students.add(new Student("Sam", 1, 7));
students.add(new Student("Ian", 2, 3));
students.add(new Student("Jordan", 2, 6));
students.add(new Student("Steven", 2, 9));
System.out.println(students);
Collections.sort(students, SchoolBus::compare);
System.out.println(students);
}
public static int compare(final Student a, final Student b) {
return a.getName().compareTo(b.getName());
}
private static final class Student {
private final int a;
private final int b;
private final String name;
public Student(final String name, final int a, final int b) {
this.name = Objects.requireNonNull(name, "name == null");
this.a = a;
this.b = b;
}
public int getA() {
return this.a;
}
public int getB() {
return this.b;
}
public String getName() {
return this.name;
}
@Override
public String toString() {
return String.format("Student: [Name=%s], [A=%s], [B=%s]", this.name, Integer.toString(this.a), Integer.toString(this.b));
}
}
}