java - 创建一个数组并尝试声明内部循环发现错误 ArrayIndexOutOfBoundsException

标签 java

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/

相关文章:

java - 如何使用可序列化对象和回调方法正确模拟 Java RMI 中的按引用传递?

java - Netbeans matisse,自定义按钮图标属性错误

java - 神经网络没有主动响应已学习的内容

Java:将多个对象绘制到一帧中

java - 如何使用 CSS 选择器

java - Java 中较小的 code-128 条形码生成

java - Gson 反序列化为 List<Object>,其中列表的通用类型作为类名给出

java - 使用加法、减法或乘法可以使 5 个数字等于目标数字吗

java - Android JUnit 测试应用类

Java - 我们如何获取选定或 Activity 框架(getSelected Frame())并将其传递给 JDialog()?