package sortpractice;
public class Employee implements Comparable<Employee> {
int id;
String name;
int age;
long salary;
public Employee(int id, String name, int age, long salary) {
this.id = id;
this.name = name;
this.age = age;
this.salary = salary;
}
public int getId() {
return this.id;
}
public String getName() {
return this.name;
}
public int getAge() {
return this.age;
}
public long getSalary() {
return this.salary;
}
public String toString() {
return "[id=" + this.id + ", name=" + this.name + ", age=" + this.age + ", salary="
+ this.salary + "]";
}
@Override
public int compareTo(Employee emp) {
return (this.id - emp.id);
}
}
<小时/>package sortpractice;
import java.util.Arrays;
public class JavaObjectSorting {
int[] id = {3, 1, 2};
String[] name = {"A", "B", "C"};
int[] age = {10, 20, 30};
long[] salary = {100, 200, 300};
public JavaObjectSorting() {
for (int i = 0; i < id.length; i++) {
Employee[] test = new Employee[i];
System.out.println(i);
test[i] = new Employee(id[i], name[i], age[i], salary[i]);
}
}
public static void main(String args[]) {
JavaObjectSorting j = new JavaObjectSorting();
}
}
最佳答案
将以下行放在 for 循环之外
Employee[] test = new Employee[id.length];
现在你的代码将像这样:
for (int i = 0; i < id.length; i++) {
test[i] = new Employee(id[i], name[i], age[i], salary[i]);
}
关于java - 创建一个数组并尝试声明内部循环发现错误 ArrayIndexOutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22169193/