1:数组是一种效率最高的存储和随机访问对象引用序列的方式
2:返回一个数组:IceCream
/**
* Created By Kevin Gauguin On 2018/1/27
* 能确保返回的数组中不包含相同的元素
*/
public class IceCream {
private static Random random = new Random(47);
private static final String[] FLAVORS = {"chocolate", "strawberry",
"swirl", "mint chip", "fudge", "raisin", "cream", "mud pie"};
public static String[] flavorSet(int n) {
if (n > FLAVORS.length) {
throw new IllegalArgumentException("set too big");
}
String[] results = new String[n];
boolean[] picked = new boolean[FLAVORS.length]; // 初始化默认为false
for (int i = 0; i < n; i++) {
int t;
do
{
t = random.nextInt(FLAVORS.length);
}
while (picked[t]);
results[i] = FLAVORS[t];
picked[t] = true;
}
return results;
}
public static void main(String[] args) {
for (int i = 0; i < 7; i++) {
System.out.println(Arrays.toString(flavorSet(4)));
}
}
}
3:Arrays.fill()可以填充整个数组,或者只填充一部分区域,但是只能用单一的数值来调用Arrays.fill().
4:java.util.Arrays类:它有一套用于数组的static实用方法,其中有6个基本方法,equals()用于比较两个数组是否相等,sort()用于对数组排序,binarySearch()用于在已经排序的数组中查找元素,toString()产生数组的String表示,Arrays.asList()将数组转换为List容器: ArraysUtil
/**
* Created By Kevin Gauguin On 2018/1/27
*/
public class ArraysUtil {
// ArraysUtil的基本方法
public static void simple() {
String[] str = {"def", "abc", "hjkl"};
// 调用数组的toString()方法
System.out.println(Arrays.toString(str));
// 排序
Arrays.sort(str);
System.out.println("排序: " + Arrays.toString(str));
// 调用转换为List容器的方法
List<String> strings = Arrays.asList(str);
System.out.println("调用转换为List容器的方法: " + strings);
int def = Arrays.binarySearch(str, "def");
System.out.println("查找 'def' 所在位置为:" + def);
}
// Arrays实用方法- - arraycopy()
public static void copy() {
int[] a = new int[19];
int[] b = new int[10];
Arrays.fill(a, 2);
Arrays.fill(b, 5);
System.arraycopy(a, 0, b, b.length/2, 5);
System.out.println("执行arraycopy函数后的结果: " + Arrays.toString(b));
}
public static void main(String[] args) {
simple();
// copy();
}
}
5:总结:在项目中优先实用容器,数组只有一点性能上的优势,但是性能出问题的地方是我通常无论如何都无法想到的。只有在已证明性能成为了问题,且切换到数组后对性能有所帮助,才应该将程序重构为数组