Java 数组新手教程一口气讲完!(≧∀≦)ゞ

Java 数组元素

Java数据类型教程 - Java数组元素

我们可以使用括在括号中的元素索引来引用数组的每个单独元素。

第一个元素的索引为0,第二个元素1,第三个元素2等。

这称为基于零的索引。数组的最后一个元素的索引是数组的长度减1。

如果我们有一个长度为5的数组,数组元素的索引将是0,1,2,3和4。

引用数组的非现有元素是一个运行时错误。

例如,在代码中使用myID [5]将抛出异常,因为myID的长度为5,而myID [5]引用的是第六个元素,它不存在。

我们可以为数组的元素赋值如下:

myID[0]   = 10;    // Assign  10  to the   first element of  myID 
myID[1]   = 20;    // Assign  20  to the   second  element of  myID 
myID[2]   = 30;    // Assign  30  to the   third  element of  myID 
myID[3]   = 40;    // Assign  40  to the   fourth  element of  myID 
myID[4]   = 50;    // Assign  50  to the   fifth element of  myID

以下语句将myID数组的第三个元素的值赋给int变量temp:

int temp  = myID[2]; // Assigns 30  to temp

数组长度

数组对象有一个名为length的公共最终实例变量,它包含数组中元素的数量。

int[] myID = new int[5]; // Create an  array of  length 5 
int len   = myID.length;      // 5  will be  assigned to len

length 是数组对象的属性。直到我们创建数组对象,我们不能使用它的length属性。

通常,使用循环访问数组的元素。

for (int i = 0 ; i < myID.length; i++)   {
    myID[i] = (i + 1)  *  10;
}

初始化数组元素

数组元素总是初始化。

基本数据类型的数组元素被初始化为其数据类型的默认值。

例如,数字数组元素初始化为零,布尔元素为false,引用类型元素为null。

以下代码说明了数组初始化:

默认情况下,intArray [0],intArray [1]和intArray [2]初始化为零。

int[]  intArray = new int[3];

bArray [0]和bArray [1]初始化为false。

boolean[] bArray  = new boolean[2];

参考类型数组的示例。strArray [0]和strArray [1]初始化为null。

String[]  strArray = new String[2]

person数组的所有100个元素都初始化为null。

Person[]  person = new Person[100];

下面说明了一个实例变量和一些局部变量的数组初始化。

public class Main {
  private boolean[] bArray = new boolean[3]; // An instance variable

  public Main() {
    for (int i = 0; i < bArray.length; i++) {
      System.out.println("bArray[" + i + "]:" + bArray[i]);
    }
  }

  public static void main(String[] args) {
    int[] myID = new int[3]; // A local array variable
    for (int i = 0; i < myID.length; i++) {
      System.out.println("myID[" + i + "]:" + myID[i]);
    }
    String[] name = new String[3]; // A local array variable
    for (int i = 0; i < name.length; i++) {
      System.out.println("name[" + i + "]:" + name[i]);
    }
  }
}

上面的代码生成以下结果。

Java 数组复制

Java数据类型教程 - Java数组复制

以下代码显示了如何使用for loop复制数组。

import java.util.Arrays;

public class Main {
  public static void main(String[] args) {
    int[] data = { 1, 2, 3, 4, 5 };

    // Expand the data array to 7 elements
    int[] eData = expandArray(data, 7);

    // Truncate the data array to 3 elements
    int[] tData = expandArray(data, 3);

    System.out.println("Original  Array: " + Arrays.toString(data));
    System.out.println("Expanded Array: " + Arrays.toString(eData));
    System.out.println("Truncated  Array: " + Arrays.toString(tData));

  }

  // Uses a for-loop to copy an array
  public static int[] expandArray(int[] oldArray, int newlength) {
    int originallength = oldArray.length;
    int[] newArray = new int[newlength];
    int elementsToCopy = 0;

    if (originallength > newlength) {
      elementsToCopy = newlength;
    } else {

      elementsToCopy = originallength;
    }
    for (int i = 0; i < elementsToCopy; i++) {
      newArray[i] = oldArray[i];
    }
    return newArray;
  }
}

上面的代码生成以下结果。

System.arraycopy

我们还可以使用System类的arraycopy()方法将数组的元素复制到另一个数组。

arraycopy()方法的签名如下:

public static  void  arraycopy(Object sourceArray, 
                               int  sourceStartPosition, 
                               Object destinationArray,
                               int destinationStartPosition, 
                               int  lengthToBeCopied)

这里,

  • sourceArray是源数组。
  • sourceStartPosition是源数组中的起始索引,元素的复制将从该起始索引开始。
  • destinationArray是目标数组。
  • destinationStartPosition是目标数组中的起始索引,将从中复制源数组的新元素。
  • lengthToBeCopied是要复制的元素数。

我们可以用下面的代码替换前面的for循环:

System.arraycopy (ids,  0, tmyIDs, 0, elementsToCopy);

以下代码显示如何使用System.arraycopy复制数组。

import java.util.Arrays;

public class Main {
  public static void main(String[] args) {
    int[] data = { 1, 2, 3, 4, 5 };

    // Copy data array to new arrays 
    int[] eData = new int[9];
    int[] tData = new int[2];
    System.arraycopy(data, 0, eData, 0, 5);
    System.arraycopy(data, 0, tData, 0, 2);

    System.out.println("Original  Array: " + Arrays.toString(data));
    System.out.println("Expanded Array: " + Arrays.toString(eData));
    System.out.println("Truncated  Array: " + Arrays.toString(tData));
  }
}

上面的代码生成以下结果。

数组克隆

我们可以使用数组的clone()方法创建数组的副本。对于原始类型,克隆的数组将具有原始数组的真实副本。

但是,对于引用类型,存储在每个元素中的对象的引用将复制到克隆的数组。

这被称为浅拷贝。在浅层复制中,两个数组的元素(原始和克隆)指的是内存中的同一个对象。

下面的代码演示了一个int数组和一个String数组的克隆。

public class Main {
  public static void main(String[] args) {
    // Create an array of 3 integers 1,2,3
    int[] ids = { 1, 2, 3 };
    int[] clonedIds = (int[]) ids.clone();

    // Create an array of 3 strings.
    String[] names = { "A", "B", "C" };
    String[] clonedNames = (String[]) names.clone();
  }
}

Java 可变长度数组

Java数据类型教程 - Java可变长度数组

Java数组不能增长。为了创建一个可扩展的数组,我们可以使用ArrayList或Vector。

ArrayList和Vector类的工作方式相同,只是Vector类中的方法是同步的,而ArrayList中的方法不同步。

ArrayList类仅适用于对象,不适用于原始数据类型。

ArrayList类是一个通用类,它将其元素的类型作为type参数。

要使用原始值,请声明一个包装类的ArrayList。例如,使用ArrayList <Integer>来处理int元素。

例子

以下代码片段说明了ArrayList类的使用:

import java.util.ArrayList;

public class Main {
  public static void main(String[] args) {
    ArrayList<Integer> ids = new ArrayList<>();

    int total = ids.size(); // total will be zero

    System.out.println("ArrayList size is  " + total);
    System.out.println("ArrayList elements are   " + ids);

    ids.add(new Integer(10)); // Adding an Integer object.
    ids.add(20); // Autoboxing
    ids.add(30); // Autoboxing

    total = ids.size(); // total will be 3

    System.out.println("ArrayList size is  " + total);
    System.out.println("ArrayList elements are   " + ids);

    ids.clear();

    total = ids.size(); // total will be 0
    System.out.println("ArrayList size is  " + total);
    System.out.println("ArrayList elements are   " + ids);
  }
}

上面的代码生成以下结果。

例2

像数组一样,ArrayList使用基于零的索引。 ArrayList的第一个元素的索引为零。

以下代码说明了如何使用for循环遍历ArrayList的元素。

import java.util.ArrayList;

public class Main {
  public static void main(String[] args) {
    ArrayList<String> namelist = new ArrayList<String>();

    // Add some names
    namelist.add("A");
    namelist.add("B");
    namelist.add("C");

    // Get the count of names in the list
    int count = namelist.size();

    for (int i = 0; i < count; i++) {
      String name = namelist.get(i);
      System.out.println(name);
    }

    namelist.remove("A");

    count = namelist.size();

    for (int i = 0; i < count; i++) {
      String name = namelist.get(i);
      System.out.println(name);
    }
  }
}

上面的代码生成以下结果。

将ArrayList/Vector转换为数组

ArrayList类有一个名为toArray()的重载方法:

Object[]     toArray( )
<T> T[]      toArray(T[ ] a)

第一个方法返回ArrayList的元素作为Object的数组。第二种方法将任何类型的数组作为参数。

以下代码显示了如何将ArrayList转换为数组。

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

public class Main {
  public static void main(String[] args) {
    ArrayList<String> al = new ArrayList<String>();
    al.add("Java");
    al.add("SQL");
    al.add("Data");

    System.out.println("ArrayList:" + al);
    String[] s1 = new String[al.size()];

    String[] s2 = al.toArray(s1);

    System.out.println("s1 == s2:" + (s1 == s2));
    System.out.println("s1:" + Arrays.toString(s1));
    System.out.println("s2:" + Arrays.toString(s2));

    s1 = new String[1];
    s1[0] = "hello"; // Store hello in first element

    s2 = al.toArray(s1);

    System.out.println("s1 == s2:" + (s1 == s2));
    System.out.println("s1:" + Arrays.toString(s1));
    System.out.println("s2:" + Arrays.toString(s2));
  }
}

上面的代码生成以下结果。

Java 数组参数

Java数据类型教程 - Java数组参数

数组参数

我们可以将数组作为参数传递给方法或构造函数。

我们传递给该方法的数组的类型必须是与形式参数类型兼容的赋值。

以下代码显示了如何将Array作为方法参数传递。

public class Main {
  public static void main(String[] args) {
    int[] num = { 1, 2 };

    System.out.println("Before  swap");
    System.out.println("#1: " + num[0]);
    System.out.println("#2: " + num[1]);

    swap(num);

    System.out.println("After  swap");
    System.out.println("#1: " + num[0]);
    System.out.println("#2: " + num[1]);
  }
  public static void swap(int[] source) {
    if (source != null && source.length == 2) {
      // Swap the first and the second elements
      int temp = source[0];
      source[0] = source[1];
      source[1] = temp;
    }
  }
}

上面的代码生成以下结果。

数组参数参考

因为数组是一个对象,所以它的引用的副本被传递给一个方法。

如果方法更改数组参数,实际参数不受影响。

import java.util.Arrays;

public class Main {
  public static void main(String[] args) {
    int[] origNum = { 1, 2, 3 };
    System.out.println("Before method  call:" + Arrays.toString(origNum));

    // Pass the array to the method
    tryArrayChange(origNum);

    System.out.println("After method  call:" + Arrays.toString(origNum));
  }

  public static void tryArrayChange(int[] num) {
    System.out.println("Inside method-1:" + Arrays.toString(num));
    // Create and store a new int array in num
    num = new int[] { 10, 20 };

    System.out.println("Inside method?2:" + Arrays.toString(num));
  }
}

上面的代码生成以下结果。

数组参数的元素

存储在数组参数的元素中的值可以在方法中始终更改。

以下代码显示了如何更改方法中的数组参数的元素。

import java.util.Arrays;

public class Main {
  public static void main(String[] args) {
    int[] origNum = { 1, 2, 3 };
    String[] origNames = { "Java", "SQL" };
    System.out.println("Before method  call, origNum:"
        + Arrays.toString(origNum));
    System.out.println("Before method  call, origNames:"
        + Arrays.toString(origNames));

    // Call methods passing the arrays 
    tryElementChange(origNum);
    tryElementChange(origNames);

    System.out.println("After method  call, origNum:"
        + Arrays.toString(origNum));
    System.out.println("After method  call, origNames:"
        + Arrays.toString(origNames));
  }

  public static void tryElementChange(int[] num) {
    if (num != null && num.length > 0) {
      num[0] = -1;
    }
  }

  public static void tryElementChange(String[] names) {
    if (names != null && names.length > 0) {
      names[0] = "T";
    }
  }
}

上面的代码生成以下结果。

例子

以下代码显示如何更改对象数组元素。

class Item {
  private double price;
  private String name;

  public Item(String name, double initialPrice) {
    this.name = name;
    this.price = initialPrice;
  }

  public double getPrice() {
    return this.price;
  }

  public void setPrice(double newPrice) {
    this.price = newPrice;
  }

  public String toString() {
    return "[" + this.name + ", " + this.price + "]";
  }
}

public class Main {
  public static void main(String[] args) {
    Item[] myItems = { new Item("Pen", 2.11), new Item("Pencil", 0.10) };
    System.out.println("Before method  call  #1:" + myItems[0]);
    System.out.println("Before method  call  #2:" + myItems[1]);

    // Call the method passing the array of Item
    tryStateChange(myItems);

    System.out.println("After method  call  #1:" + myItems[0]);
    System.out.println("After method  call  #2:" + myItems[1]);
  }

  public static void tryStateChange(Item[] allItems) {
    if (allItems != null && allItems.length > 0) {
      allItems[0].setPrice(0.38);
    }
  }
}

上面的代码生成以下结果。

Java 多维数组 

Java数据类型教程 - Java多维数组

我们可以在二维数组中存储表格数据。

使用数组声明中每个维度的一对括号[]来声明多维数组。

例如,如下所示定义int的二维数组:

int[][] table;

这里,table是一个引用变量,可以保存对int的二维数组的引用。

可以创建具有三行和两列的二维数组int,如下所示:

table = new int[3][2];

多维数组中每个维度的索引都是从零开始的。

表数组的每个元素可以作为表[rownumber] [columnNumber]访问。

行号和列号始终从零开始。

例如,以下代码将值分配给表数组中的第一行和第二列,如图所示:

table[0][1] = 32;

您可以将值1分配给第三行和第一列,如下所示:

table[2][0] = 1;

我们必须在创建多维数组时指定至少第一级数组的维度。

例如:

table = new int[3][];

我们必须在创建多维数组时指定至少第一级数组的维度。

此时仅存在表[0],表[1]和表[2]。

他们指的是null。 table.length的值为3。

table [0],table [1]和table [2]是int数组,我们可以将它们赋值为

table[0] = new int[2]; // Create two  columns  for row 1 
table[1] = new int[2]; // Create two  columns  for row 2 
table[2] = new int[2]; // Create two  columns  for row 3

Java可以为每行创建一个具有不同列数的二维数组。这样的数组称为粗糙数组。

例子

以下代码显示了如何创建一个不规则数组。

public class Main {
  public static void main(String[] args) {
    // Create a two-dimensional array of 3 rows
    int[][] raggedArray = new int[3][];

    // Add 2 columns to the first row
    raggedArray[0] = new int[2];

    // Add 1 column to the second row
    raggedArray[1] = new int[1];

    // Add 3 columns to the third row
    raggedArray[2] = new int[3];

    // Assign values to all elements of raggedArr
    raggedArray[0][0] = 1;
    raggedArray[0][1] = 2;
    raggedArray[1][0] = 3;
    raggedArray[2][0] = 4;
    raggedArray[2][1] = 5;
    raggedArray[2][2] = 6;

    // Print all elements. One row at one line
    System.out.println(raggedArray[0][0] + "\t" + raggedArray[0][1]);
    System.out.println(raggedArray[1][0]);
    System.out.println(raggedArray[2][0] + "\t" + raggedArray[2][1] + "\t"
        + raggedArray[2][2]);
  }
}

上面的代码生成以下结果。

访问多维数组的元素

通常,使用嵌套for循环来填充多维数组。

用于处理多维数组的for循环数等于数组中的维数。

以下代码显示了如何访问多维数组的元素。

public class Main {
  public static void main(String[] args) {
    int[][] myArray = new int[3][];
    myArray[0] = new int[2];
    myArray[1] = new int[1];
    myArray[2] = new int[3];

    // Populate the ragged array using for loops
    for (int i = 0; i < myArray.length; i++) {
      for (int j = 0; j < myArray[i].length; j++) {
        myArray[i][j] = i + j;
      }
    }

    // Print the array using for loops
    for (int i = 0; i < myArray.length; i++) {
      for (int j = 0; j < myArray[i].length; j++) {
        System.out.print(myArray[i][j] + "\t");
      }

      // Add a new line after each row is printed
      System.out.println();
    }
  }
}

上面的代码生成以下结果。

初始化多维数组

我们可以通过在声明时或在创建时提供值列表来初始化多维数组的元素。

每个维度的初始值数量将决定数组中每个维度的长度。

级别的值的列表用大括号括起来。

对于二维数组,每行的值列表都包含在一对大括号中,如下所示:

int[][] arr = {{10, 20, 30},   
               {1, 2},   
               {2, 3, 4, 5}};

此语句创建一个具有三行的二维数组。

以下代码显示如何初始化一个二维String数组:

String[][] acronymlist = {{"A", "a"},
                          {"B", "b"},
                          {"C", "c"}};

我们可以在创建多维数组时初始化多维数组的元素。

int[][] arr = new int[][]{{1, 2},   {3,4,5}};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值