來(lái)自對(duì)on java的學(xué)習(xí)
初始化
對(duì)象數(shù)組存儲(chǔ)的是對(duì)象的引用,而基元數(shù)組則直接存儲(chǔ)基本數(shù)據(jù)類型的值侄旬。
使用大括號(hào),多維數(shù)組用大括號(hào)分開(kāi),并且多維數(shù)組可以變長(zhǎng):
import java.util.*;
public class MultidimensionalObjectArrays {
? public static void main(String[] args) {
? ? BerylliumSphere[][] spheres = {
? ? ? { new BerylliumSphere(), new BerylliumSphere() },
? ? ? { new BerylliumSphere(), new BerylliumSphere(),
? ? ? ? new BerylliumSphere(), new BerylliumSphere() },
? ? ? { new BerylliumSphere(), new BerylliumSphere(),
? ? ? ? new BerylliumSphere(), new BerylliumSphere(),
? ? ? ? new BerylliumSphere(), new BerylliumSphere(),
? ? ? ? new BerylliumSphere(), new BerylliumSphere() },
? ? };
? ? System.out.println(Arrays.deepToString(spheres));
? }
}
/* Output:
[[Sphere 0, Sphere 1], [Sphere 2, Sphere 3, Sphere 4,
Sphere 5], [Sphere 6, Sphere 7, Sphere 8, Sphere 9,
Sphere 10, Sphere 11, Sphere 12, Sphere 13]]
*/
如果是整數(shù)等基元數(shù)組,可以使用自動(dòng)裝箱:
// arrays/AutoboxingArrays.java
import java.util.*;
public class AutoboxingArrays {
? public static void main(String[] args) {
? ? Integer[][] a = { // Autoboxing:
? ? ? { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 },
? ? ? { 21, 22, 23, 24, 25, 26, 27, 28, 29, 30 },
? ? ? { 51, 52, 53, 54, 55, 56, 57, 58, 59, 60 },
? ? ? { 71, 72, 73, 74, 75, 76, 77, 78, 79, 80 },
? ? };
? ? System.out.println(Arrays.deepToString(a));
? }
}
/* Output:
[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [21, 22, 23, 24, 25,
26, 27, 28, 29, 30], [51, 52, 53, 54, 55, 56, 57, 58,
59, 60], [71, 72, 73, 74, 75, 76, 77, 78, 79, 80]]
*/
一些方法的使用
Arrays.deepToString() 可以用于轉(zhuǎn)化多維數(shù)組并直接用System.out.print打印k;
Arrays.fill()?該方法將單個(gè)值復(fù)制到整個(gè)數(shù)組稳懒,或者在對(duì)象數(shù)組的情況下,將相同的引用復(fù)制到整個(gè)數(shù)組;
Arrays.setAll()?使用一個(gè)生成器并生成不同的值慢味,可以選擇基于數(shù)組的索引元素(通過(guò)訪問(wèn)當(dāng)前索引场梆,生成器可以讀取數(shù)組值并對(duì)其進(jìn)行修改)。static Arrays.setAll()的重載簽名為:
void setAll(int[] a, IntUnaryOperator gen)
void setAll(long[] a, IntToLongFunction gen)
void setAll(double[] a, IntToDoubleFunctiongen)
<T> void setAll(T[] a, IntFunction<?extendsT> gen)
除了int,long,double有特殊的版本纯路,其他的一切都由泛型版本處理或油。生成器不是Supplier因?yàn)樗鼈儾粠?shù),并且必須將int數(shù)組索引作為參數(shù)驰唬。
Stream 生成Array:? a1 = Stream.generate(new Count.Boolean()).limit(SZ + 1).toArray(Boolean[]::new);