第十一章: Collections of Objects数组部分
the Java utilities library has a reasonably complete set of container classes
1、Arrays
There are three issues that distinguish arrays from other types of containers:
efficiency, type, and the ability to hold primitives. The array is the most efficient way
that Java provides to store and randomly access a sequence of object references. The array
is a simple linear sequence, which makes element access fast, but you pay for this speed;
when you create an array object, its size is fixed and cannot be changed for the lifetime of that
array object.数组可以持有 primitive,而容器则不行,容器将所含的对象均看成object的.arrays of objects
hold references, but arrays of primitives hold the primitive values directly.
// Arrays of objects:
Weeble[] a; // Local uninitialized variable
Weeble[] b = new Weeble[5]; // Null references
Weeble[] c = new Weeble[4];
for(int i = 0; i < c.length; i++)
if(c[i] == null) // Can test for null reference
c[i] = new Weeble();
// Aggregate initialization:
Weeble[] d = {
new Weeble(), new Weeble(), new Weeble()
};
// Dynamic aggregate initialization:
a = new Weeble[] {
new Weeble(), new Weeble()
};
a = d;
2、The Arrays class
which holds a set of static methods that perform utility functions for arrays. There are four basic methods: equals( ), to compare two arrays for equality; fill( ), to fill an array with a value; sort( ), to sort the array; and binarySearch( ), to find an element in a sorted array. All of these methods are overloaded for all the primitive types and Objects. In addition, there’s a single asList( ) method that takes any array and turns it into a List container
2.1)Filling an array
int[] a1 = new int[6];
String[] a2 = new String[6];
Arrays.fill(a1, 19);
System.out.println("a1 = " + Arrays2.toString(a1));
Arrays.fill(a2, "Hello");
System.out.println("a2 = " + Arrays.asList(a2));
// Manipulating ranges:
Arrays.fill(a2, 3, 5, "World");
//因a2持的是refrence,因用asList将其转换成list
System.out.println("a2 = " + Arrays.asList(a2));
2.2) Copying an array--System.arraycopy( ), which can make much
faster copies of an array than if you use a for loop to perform the copy by
hand.
int[] i = new int[7];
int[] j = new int[10];
Arrays.fill(i, 47);
Arrays.fill(j, 99);
System.out.println("i = " + Arrays2.toString(i));
System.out.println("j = " + Arrays2.toString(j));
System.arraycopy(i, 0, j, 0, i.length);
System.out.println("j = " + Arrays2.toString(j));
// Objects:
Integer[] u = new Integer[10];
Integer[] v = new Integer[5];
Arrays.fill(u, new Integer(47));
Arrays.fill(v, new Integer(99));
System.out.println("u = " + Arrays.asList(u));
System.out.println("v = " + Arrays.asList(v));
System.arraycopy(v, 0, u, u.length/2, v.length);
System.out.println("u = " + Arrays.asList(u));
The arguments to arraycopy( ) are the source array, the offset into
the source array from whence to start copying, the destination array, the
offset into the destination array where the copying begins, and the
number of elements to copy.
2.3) Comparing arrays
import com.bruceeckel.simpletest.*;
import java.util.*;
public class ComparingArrays {
private static Test monitor = new Test();
public static void main(String[] args) {
int[] a1 = new int[10];
int[] a2 = new int[10];
Arrays.fill(a1, 47);
Arrays.fill(a2, 47);
System.out.println(Arrays.equals(a1, a2));
a2[3] = 11;
System.out.println(Arrays.equals(a1, a2));
String[] s1 = new String[5];
Arrays.fill(s1, "Hi");
String[] s2 = {"Hi", "Hi", "Hi", "Hi", "Hi"};
System.out.println(Arrays.equals(s1, s2));
monitor.expect(new String[] {
"true",
"false",
"true"
});
}
} ///:~
2.4)Array element comparisons
Java has two ways to provide comparison functionality. The first is with the “natural” comparison method that is imparted to a class by implementing the java.lang.Comparable interface. This is a very simple interface with a single method, compareTo( ). This method takes another Object as an argument and produces a negative value if the current object is less than the argument, zero if the argument is equal, and a positive value if the current object is greater than the argument.second,use a strategy, create a strategy by defining a separate class that implements an interface called Comparator. This has two methods, compare( ) and equals( ).
// 一、Implementing Comparable in a class.-采用回调callback技术--------
---------
import com.bruceeckel.util.*;
import java.util.*;
public class CompType implements Comparable {
int i;
int j;
public CompType(int n1, int n2) {
i = n1;
j = n2;
}
public String toString() {
return "[i = " + i + ", j = " + j + "]";
}
public int compareTo(Object rv) {
int rvi = ((CompType)rv).i;
return (i < rvi ? -1 : (i == rvi ? 0 : 1));
}
private static Random r = new Random();
public static Generator generator() {
return new Generator() {
public Object next() {
return new CompType(r.nextInt(100),r.nextInt(100));
}
};
}
public static void main(String[] args) {
CompType[] a = new CompType[10];
Arrays2.fill(a, generator());
System.out.println(
"before sorting, a = " + Arrays.asList(a));
Arrays.sort(a);
System.out.println(
"after sorting, a = " + Arrays.asList(a));
}
} ///:~
//二、 Implementing a Comparator for a class.采用策略模式strategy
design //pattern通过实现comparator接口来定义策略对象-------------------------------
import com.bruceeckel.util.*;
import java.util.*;
class CompTypeComparator implements Comparator {
public int compare(Object o1, Object o2) {
int j1 = ((CompType)o1).j;
int j2 = ((CompType)o2).j;
return (j1 < j2 ? -1 : (j1 == j2 ? 0 : 1));
}
}
public class ComparatorTest {
public static void main(String[] args) {
CompType[] a = new CompType[10];
Arrays2.fill(a, CompType.generator());
System.out.println(
"before sorting, a = " + Arrays.asList(a));
Arrays.sort(a, new CompTypeComparator());
System.out.println(
"after sorting, a = " + Arrays.asList(a));
}
} ///:~
2.5) Sorting an array
见2.4)
2.6)Searching a sorted array--Once an array is sorted, you can perform a
fast search for a particular item by using Arrays.binarySearch( ).
If you have sorted an object array using a Comparator ,you must include
that same Comparator when you perform a binarySearch( )
// Searching with a Comparator.
import com.bruceeckel.simpletest.*;
import com.bruceeckel.util.*;
import java.util.*;
public class AlphabeticSearch {
private static Test monitor = new Test();
public static void main(String[] args) {
String[] sa = new String[30];
Arrays2.fill(sa, new Arrays2.RandStringGenerator(5));
AlphabeticComparator comp = new AlphabeticComparator();
Arrays.sort(sa, comp);
int index = Arrays.binarySearch(sa, sa[10], comp);
System.out.println("Index = " + index);
monitor.expect(new String[] {
"Index = 10"
});
}
} ///:~