Arrays定义了很多与数组有关的基本操作
public static boolean equals (int[ ] a,int [ ] b)
public static void fill(int[] a,int val)
public static void sort(int[ ] a)
public static int binarySearch(int[ ] a,int key)
public static String toString (int[ ] a)
public class ArraysDemo { public static void main(String[] args) { int i1[] = { 1, 2, 3, 4, 5, 6 }; // 两个数组内容一样 int i2[] = { 6, 5, 4, 3, 2, 1 }; // 两个数组内容一样 Arrays.sort(i2); System.out.println(Arrays.equals(i1, i2)); Arrays.fill(i2, 3); // 将数组2的内容全部填充为3 System.out.println(Arrays.toString(i2));// 输出内容 } }
class Student implements Comparable<Student> { // 实现比较器,并指定泛型 private int stuno; private String name; private int age; private float score; public Student(int stuno, String name, int age, float score) { this.stuno = stuno; this.name = name; this.age = age; this.score = score; } public int compareTo(Student stu) { if (this.score > stu.score) { return -1; } else if (this.score < stu.score) { return 1; } else { if (this.age > stu.age) { return 1; } else if (this.age < stu.age) { return -1; } else { return 0; } } } public String toString() { // 覆写toString() return "学生编号:" + this.stuno + ";姓名:" + this.name + ";年龄:" + this.age + ";成绩:" + this.score; } } public class CompareableDemo01 { public static void main(String[] args) { Student stu[] = { new Student(1, "张三", 21, 99.1f), new Student(2, "李四", 20, 99.1f), new Student(3, "王五", 21, 89.1f), new Student(4, "赵六", 21, 80.1f), new Student(5, "孙七", 19, 80.1f) }; System.out.println("============== 数组声明之前 ==============="); print(stu); System.out.println("============== 数组排序之后 ==============="); Arrays.sort(stu);// 排序 print(stu); } public static void print(Student stu[]) { for (int i = 0; i < stu.length; i++) { System.out.println(stu[i]); } } }
通过实现cloneable可以使得类的实例化对象具有被克隆能力
class Person implements Cloneable {// 表示此类的对象可以被克隆 private String name; public Person(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String toString() { return "姓名:" + this.getName(); } public Object clone() throws CloneNotSupportedException { return super.clone(); } } public class CloneDemo { public static void main(String[] args) throws CloneNotSupportedException { Person per1 = new Person("张三"); Person per2 = (Person)per1.clone() ; per2.setName("李四") ; System.out.println(per1) ; System.out.println(per2) ; } }