Cách sử dụng đối tượng Array

Trong post này:

  • Khai báo mảng
  • Khởi tạo các phần tử của mảng
  • Copy Mảng
  • Copy mảng dùng System.arraycopy
  • Clone một mảng
  • Lấy độ dài của mảng
  • Convert giá trị của mảng thành String
  • Convert vector sang Array
  • In giá trị trong mảng
  • Mảng reference
  • In giá trị mảng theo phần tử
  • Mảng đa chiều
  • Truy vấn mảng đa chiều

1. Khai báo mảng

public class Main {
  public static void main(String[] args) {
    int[] iArr = new int[1];
    int[][] iiArr = new int[1][1];
    int[][][] iiiArr = new int[1][1][1];
    String[] sArr = { "A", "B" };
    String[][] ssArr = { { "A" }, { "B" } };
    String[][][] sssArr = {}; // A 3D empty array of string

    // Print the class name for all arrays
    System.out.println("int[]:" + getClassName(iArr));
    System.out.println("int[][]:" + getClassName(iiArr));
    System.out.println("int[][][]:" + getClassName(iiiArr));
    System.out.println("String[]:" + getClassName(sArr));
    System.out.println("String[][]:" + getClassName(ssArr));
    System.out.println("String[][][]:" + getClassName(sssArr));
  }
  public static String getClassName(Object obj) {
    Class c = obj.getClass();
    String className = c.getName();
    return className;
  }
}

2. Khởi tạo các phần tử của mảng

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]);
    }
  }
}

3. Copy Mảng

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;
  }
}

4. Copy mảng dùng 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));
  }
}

5. Clone một mảng

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();
  }
}

6. Lấy độ dài của mảng

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);
  }
}

7. Convert giá trị của mảng thành String

public class Main {
  public static void main(String[] args) {
    String s1 = String.valueOf('C'); // s1 has "C"
    String s2 = String.valueOf("10"); // s2 has "10"
    String s3 = String.valueOf(true); // s3 has "true"
    String s4 = String.valueOf(2014); // s4 has "2014"
  }
}

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);
    }
  }
}

8. Convert vector sang Array

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));
  }
}

9. In giá trị trong mảng

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;
    }
  }
}

10. Mảng reference

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));
  }
}

11. In giá trị mảng theo phần tử

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);
    }
  }
}

12. Mảng đa chiều

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]);
  }
}

13. Truy vấn mảng đa chiều

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();
    }
  }
}

Rate this post
Click Here to Leave a Comment Below 0 comments