Variables
Primitive Data Types
Data Type | Length | Range | Default Value | Literal |
---|---|---|---|---|
byte | 8-bit | − 128 ∼ 127 -128\sim127 −128∼127 | 0 | - |
short | 16 bit | − 32 , 768 ∼ 32 , 767 -32,768\sim32,767 −32,768∼32,767 | 0 | |
int | 32 bit | − 2 31 ∼ 2 31 − 1 -2^{31}\sim2^{31}-1 −231∼231−1 | 0 | 26, 0x1a, 0b11010 |
long | 64 bit | − 2 63 ∼ 2 63 − 1 -2^{63}\sim2^{63}-1 −263∼263−1 | 0 | |
float | 32 bit | 0L | 123.4, 1.234e2, 123.4f | |
double | 64 bit | 0.0f | ||
boolean | 1 bit | false | ||
char | 16 bit | ‘\u0000’ |
Arrays
Creating, Initializing and Accessing an Array
// 方法1
int[] anArray = {
100, 200, 300,
400, 500, 600,
700, 800, 900, 1000
};
// 多维数组
String[][] names = {
{"Mr. ", "Mrs. ", "Ms. "},
{"Smith", "Jones"}
};
Java中的多维数组和C中多为数组的区别:以2维数组为例,Java中的2维数组每一行可以有不同的长度。
**数组的长度: **anArray.length
属性
复制数组
System
类中有一个arratcopy
方法:public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
Arrays.copyOfRange(T[] original, int from, int to)
Class java.util.Arrays
java中关于数组的许多实用的操作都放在了Arrays
类中。
函数 | 功能 |
---|---|
public static <T> List<T> asList(T... a) | Returns a fixed-size list view backed by the specified array. |
static int binarySearch(int[] a, int key) static int binarySearch(int[] a, int fromIndex, int toIndex, int key) | 搜索,返回key的index,否则返回 − ( i n s e r t i o n p o i n t ) − 1 -(insertion point)-1 −(insertionpoint)−1 |
static boolean equals(char[] a, char[] a2) static boolean equals(char[] a, int aFromIndex, int aToIndex, char[] b, int bFromIndex, int bToIndex) | 比较是否相等 |
static void fill(int[] a, int val) static void fill(int[] a, int fromIndex, int toIndex, int val) | 填充 |
static void sort(int[] a) static void sort(int[] a, int fromIndex, int toIndex) | 按升序排列 |
如果有两个数组a, b, 他们有相同的内容,但是a和b没有重写hashcode()方法,也就是说调用a.equals(b)的话时没有办法得到true的,如果要根据内容判断两数组是否相等,需要使用Arrays.equals(T[] a, T[] b)方法,同时Arrays.hashCode(T[] a)方法也会根据数组的内容生成相应的hash code。