Java Append Array (1D,2D) |
Java Append Array (1D,2D) บทความนี้จะเป็นตัวอย่างการเขียน Java กับ Array ด้วยการรวมค่า Array หรือ Append เข้าด้วยกัน มีประโยชน์ในกรณีที่ต้องการทำค่า Array จำนวน 2 ค่ามารวมค่ากัน ทั้ง Array แบบ 1 มิติ (1 Dimensional) และ 2 มิติ (2 Dimensional)
Example 1 การรวมค่า Array แบบ 1 มิติ
MyClass.Java
package com.java.myapp;
public class MyClass {
public static String[] append(String[] a, String[] b) {
String[] result = new String[a.length + b.length];
System.arraycopy(a, 0, result, 0, a.length);
System.arraycopy(b, 0, result, a.length, b.length);
return result;
}
public static void main(String[] args) {
String arr[] = {"a","b","c","d","e"};
String new_array1[] = {"g","h","i","j","k"};
arr = append(arr,new_array1);
String new_array2[] = {"l","m","n","o","p"};
arr = append(arr,new_array2);
for(int i=0; i<arr.length; i++)
{
System.out.println("Value index["+i+"] = " + arr[i]);
}
}
}
Output
Value index[0] = a
Value index[1] = b
Value index[2] = c
Value index[3] = d
Value index[4] = e
Value index[5] = g
Value index[6] = h
Value index[7] = i
Value index[8] = j
Value index[9] = k
Value index[10] = l
Value index[11] = m
Value index[12] = n
Value index[13] = o
Value index[14] = p
Example 2 การรวมค่า Array แบบ 2 มิติ
MyClass.Java
package com.java.myapp;
public class MyClass {
public static String[][] append(String[][] a, String[][] b) {
String[][] result = new String[a.length + b.length][];
System.arraycopy(a, 0, result, 0, a.length);
System.arraycopy(b, 0, result, a.length, b.length);
return result;
}
public static void main(String[] args) {
String[][] arr = {{"CustomerID","Name", "Email",
"CountryCode", "Budget", "Used"}} ;
String[][] new_array1 = {{"C001"
,"Win Weerachai"
,"[email protected]"
,"TH"
,"1000000"
,"600000"}};
arr = append(arr,new_array1);
String[][] new_array2 = {{"C002"
,"John Smith"
,"[email protected]"
,"UK"
,"2000000"
,"800000"}};
arr = append(arr,new_array2);
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
String text = arr[i][j];
System.out.println("Value index["+i+"]["+j+"] = " + text);
}
System.out.println("==============================");
}
}
}
Code
Value index[0][0] = CustomerID
Value index[0][1] = Name
Value index[0][2] = Email
Value index[0][3] = CountryCode
Value index[0][4] = Budget
Value index[0][5] = Used
==============================
Value index[1][0] = C001
Value index[1][1] = Win Weerachai
Value index[1][2] = [email protected]
Value index[1][3] = TH
Value index[1][4] = 1000000
Value index[1][5] = 600000
==============================
Value index[2][0] = C002
Value index[2][1] = John Smith
Value index[2][2] = [email protected]
Value index[2][3] = UK
Value index[2][4] = 2000000
Value index[2][5] = 800000
==============================
|