Bài viết này sẽ hướng dẫn cách sử dụng phương thức "Object[] toArray()" để sao chép các giá trị của ArrayList thành mảng Object.
CopyElementsOfArrayListToObjectArray.java
/**
* @(#)CopyElementsOfArrayListToObjectArray.java
*
* CopyElementsOfArrayListToObjectArray application
*
* @author BUI NGOC SON
* @version 1.00 2013/10/28
*/
import java.util.ArrayList ;
public class CopyElementsOfArrayListToObjectArray
{
public static void main(String[] args)
{
//Khia báo đối tượng mảng.
//Declare an ArrayList object
ArrayList arrayList = new ArrayList();
// Gán giá trị vào ArrayList
// Add elements to ArrayList
arrayList.add("One");
arrayList.add("Two");
arrayList.add("Three");
arrayList.add("For");
arrayList.add("Five");
/*
* Để sao chép tất cả các gái trị của Arraylist thành mảng Object ta dùng
* phương thức Object[] toArray().
*
* To copy all elements of java ArrayList into object array use
* Object[] toArray() method.
*/
Object[] objArray = arrayList.toArray();
// In các giá trị mảng Object.
// Print all elements of Object array
System.out.println("ArrayList elements are copied into an Object Array");
for (int index = 0; index < objArray.length; index++)
{
System.out.println(objArray[index]);
}
System.out.println("\n -- VNLIVES.NET -- ");
}
}
* @(#)CopyElementsOfArrayListToObjectArray.java
*
* CopyElementsOfArrayListToObjectArray application
*
* @author BUI NGOC SON
* @version 1.00 2013/10/28
*/
import java.util.ArrayList ;
public class CopyElementsOfArrayListToObjectArray
{
public static void main(String[] args)
{
//Khia báo đối tượng mảng.
//Declare an ArrayList object
ArrayList arrayList = new ArrayList();
// Gán giá trị vào ArrayList
// Add elements to ArrayList
arrayList.add("One");
arrayList.add("Two");
arrayList.add("Three");
arrayList.add("For");
arrayList.add("Five");
/*
* Để sao chép tất cả các gái trị của Arraylist thành mảng Object ta dùng
* phương thức Object[] toArray().
*
* To copy all elements of java ArrayList into object array use
* Object[] toArray() method.
*/
Object[] objArray = arrayList.toArray();
// In các giá trị mảng Object.
// Print all elements of Object array
System.out.println("ArrayList elements are copied into an Object Array");
for (int index = 0; index < objArray.length; index++)
{
System.out.println(objArray[index]);
}
System.out.println("\n -- VNLIVES.NET -- ");
}
}
Sau khi chạy chương trình bạn sẽ được kết quả như hình bên dưới.
No comments:
Post a Comment