Created
January 19, 2019 13:16
-
-
Save ilhamarrouf/e1e9f0c2e19fc8efd8a2ffb4037e11be to your computer and use it in GitHub Desktop.
Duplikat array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Arrays; | |
public class ExampleDuplicateArray { | |
public static void main(String[] args) { | |
int[] source = {1,2,3,4,5,6,7,8,9}; | |
int[] source1 = {1,2,3}; | |
int[] destination = null; | |
System.out.println("Source array = " + Arrays.toString(source)); | |
destination = copyFirstFiveFieldsOfArrayUsingSystem(source); | |
System.out.println("Duplikat array di index pertama sampai kelima jika tersedia. Hasil array = " + Arrays.toString(destination)); | |
destination = copyFirstFiveFieldsOfArrayUsingSystem(source1); | |
System.out.println("Duplikat array di index pertama sampai kelima jika tersedia. Hasil array = " + Arrays.toString(destination)); | |
destination = copyFullArrayUsingSystem(source); | |
System.out.println("Duplikat semua index array menggunakan fungsi System.copyarray(). Hasil array = " + Arrays.toString(destination)); | |
destination = copyFullArrayUsingClone(source); | |
System.out.println("Duplikat semua index array menggunakan fungsi clone(). Hasil array = " + Arrays.toString(destination)); | |
destination = copyFullArrayUsingArrayCopyOf(source); | |
System.out.println("Duplikat semua index array menggunakan fungsi Array.copyOf(). Hasil array = " + Arrays.toString(destination)); | |
destination = copyLastThreeUsingArrayCopyOfRange(source); | |
System.out.println("Duplikat index ketiga terakhir dari array menggunkan fungsi Arrays.copyOfRange() function. Hasil array = " + Arrays.toString(destination)); | |
} | |
private static int[] copyFirstFiveFieldsOfArrayUsingSystem(int[] source) { | |
if(source.length > 5){ | |
int[] temp = new int[5]; | |
System.arraycopy(source, 0, temp, 0, 5); | |
return temp; | |
}else{ | |
int[] temp = new int[source.length]; | |
System.arraycopy(source, 0, temp, 0, source.length); | |
return temp; | |
} | |
} | |
private static int[] copyFullArrayUsingArrayCopyOf(int[] source) { | |
return Arrays.copyOf(source, source.length); | |
} | |
private static int[] copyFullArrayUsingSystem(int[] source) { | |
int[] temp = new int[source.length]; | |
System.arraycopy(source, 0, temp, 0, source.length); | |
return temp; | |
} | |
private static int[] copyLastThreeUsingArrayCopyOfRange(int[] source) { | |
return Arrays.copyOfRange(source, source.length-3, source.length); | |
} | |
private static int[] copyFullArrayUsingClone(int[] source) { | |
return source.clone(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment