copyOf()
--------
Syntax:
copyOf(int[] original, int newLength)
----eg.
public static void main(String args[])
{
// initializing an array original
int[] org = new int[] {1, 2 ,3};
System.out.println("Original Array");
for (int i = 0; i < org.length; i++)
System.out.print(org[i] + " ");
// copying array org to copy
int[] copy = Arrays.copyOf(org, 5);
// Changing some elements of copy
copy[3] = 11;
copy[4] = 55;
System.out.println("\nNew array copy after modifications:");
for (int i = 0; i < copy.length; i++)
System.out.print(copy[i] + " ");
}
-----------------------------------------------------------------------------------------
--System.arraycopy()
--
Syntax :
public static void
arraycopy(Object source_arr, int sourcePos,Object dest_arr, int destPos, int len)
---eg.
public static void main(String[] args)
{
int s[] = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
int d[] = { 15, 25, 35, 45, 55, 65, 75, 85, 95, 105};
int source_arr[], sourcePos, dest_arr[], destPos, len;
source_arr = s;
sourcePos = 3;
dest_arr = d;
destPos = 5;
len = 4;
// Print elements of source
System.out.print("source_array : ");
for (int i = 0; i < s.length; i++)
System.out.print(s[i] + " ");
System.out.println("");
System.out.println("sourcePos : " + sourcePos);
// Print elements of source
System.out.print("dest_array : ");
for (int i = 0; i < d.length; i++)
System.out.print(d[i] + " ");
System.out.println("");
System.out.println("destPos : " + destPos);
System.out.println("len : " + len);
// Use of arraycopy() method
System.arraycopy(source_arr, sourcePos, dest_arr,
destPos, len);
// Print elements of destination after
System.out.print("final dest_array : ");
for (int i = 0; i < d.length; i++)
System.out.print(d[i] + " ");
}
-----------------------------------------------------------------------------------------
Object[] obj = list.toArray();//ArrayList to Array
for copying arraylist to array
---------------------------
---------------------------
1.List<Integer> list1 = new ArrayList<Integer>(Arrays.asList(ia)); //copy
2.List<Integer> list2 = Arrays.asList(ia);
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
// creating Arrays of String type
String a[] = new String[] { "A", "B", "C", "D" };
// getting the list view of Array
List<String> list = Arrays.asList(a);
// printing the list
System.out.println("The list is: " + list);
}
catch (NullPointerException e) {
System.out.println("Exception thrown : " + e);
}
}
}
Output:
The list is: [A, B, C, D]
----------------------------------
No comments:
Post a Comment