CSE11-无代写
时间:2023-08-26
CSE 11 – Intro to Programming, Expedited
1
Arrays class in Java
It is a utility class that can help processing arrays in Java.
import java.util.Arrays;
public class ArraysDemo {
public static void main(String[] args) {
//1. copyof to make a deep copy
int[] arr = new int[] { 1, 3, 5, 7, 9, 10, 8, 6, 4, 2, 0 };
// this is deep copy
int[] intcopy = Arrays.copyOf(arr, arr.length);
StringBuilder [] names = new StringBuilder[3];
names[0] = new StringBuilder("Paul");
names[1] = new StringBuilder("Christine");
names[2] = new StringBuilder("Rick");
//this is deep copy of the reference, not the object
StringBuilder[] namescopy = Arrays.copyOf(names, 3);
//2. copyofRange from to. It is allowed to have a bigger range
int [] part1 = Arrays.copyOfRange(arr, 0, 3);//not including 3
System.out.println(Arrays.toString(part1));
//3. fill - fill in the array with some value
int [] empty = new int[10];
Arrays.fill(empty, -1);
System.out.println(Arrays.toString(empty));
//4. equals - deep comparison
int [] arr1 = new int[]{1, 3, 5};
int [] arr2 = new int[]{2, 4, 6};
System.out.println(Arrays.equals(arr1, arr2));
//5. sort - change the array itself
int [] orig = new int[]{2, -4, 5, 6, -1, -1, -3};
String[] classes = new String[]{"cse11", "bio101", "Zoology121", "Anth202"};
Arrays.sort(orig);
Arrays.sort(classes);
System.out.println(Arrays.toString(orig));
System.out.println(Arrays.toString(classes));