如何解决尝试在数组中打印附加对象时出现的 ArrayIndexOutOfBoundsException 错误?

How to solve ArrayIndexOutOfBoundsException error on trying to print appended object in an array?

当我 运行 我的代码时,它给我一个错误如下:

 Exception in thread "main" tony
 java.lang.ArrayIndexOutOfBoundsException: 1
 at tt.main(tt.java:17)

代码如下:

import java.util.ArrayList;
import java.util.Arrays;

public class tt {


   static int oldAge[];
   static Integer ages[];
   static ArrayList<Integer> ageObject;

public static void main(String args[]){

    System.out.println("tony");
    setAges();


        System.out.println(ages[1].intValue());
    System.out.println(oldAge[2]);



   }

   public static void setAges(){


    oldAge = new int[3];

     oldAge[0] = 50;
     oldAge[1] = 60;
     oldAge[2] = 70;

     ages = new Integer[1];
     ages[0] = 50;

     ageObject = new ArrayList<Integer>(Arrays.asList(ages));

 for(int x =0; x < oldAge.length; x++){

  if(oldAge[x] == 60){
    ageObject.add(oldAge[x]);
 }
  else if(oldAge[x] == 56){
    ageObject.add((Integer)(oldAge[x]));
 }
  else if(oldAge[x] == 70){
    ageObject.add((Integer)(oldAge[x]));
 }



       }

     }

  }

我想让代码打印新增加的年龄值,应该是 60。

这一行

System.out.println(ages[1].intValue());

不正确。 ages 恰好是一个元素。应该是

System.out.println(ages[0].intValue());

我得到的没有其他变化

tony
50
70

要获得 60,您需要打印 oldAge 的第二个元素。喜欢,

System.out.println(oldAge[1]);