java如何定义数组并赋值

avatar
作者
猴君
阅读量:0

在Java中,可以通过以下方式定义数组并赋值:

  1. 使用数组初始化器(Array Initializer):
int[] numbers = {1, 2, 3, 4, 5}; String[] names = {"Alice", "Bob", "Charlie"}; 
  1. 使用关键字new创建数组并赋值:
int[] numbers = new int[5]; numbers[0] = 1; numbers[1] = 2; numbers[2] = 3; numbers[3] = 4; numbers[4] = 5;  String[] names = new String[3]; names[0] = "Alice"; names[1] = "Bob"; names[2] = "Charlie"; 
  1. 使用循环遍历数组并赋值:
int[] numbers = new int[5]; for (int i = 0; i < numbers.length; i++) {     numbers[i] = i + 1; }  String[] names = new String[3]; String[] characters = {"Alice", "Bob", "Charlie"}; for (int i = 0; i < names.length; i++) {     names[i] = characters[i]; } 

    广告一刻

    为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!