Java數組
對數組的基本看法是,你可以創建並組裝它們,通過使用整型索引值訪問它們的元素,並且它們的尺寸不能改變。但有時候你需要在數組上執行更加複雜的操作,並且你可能會評估到底是使用數組還更加靈活的容器。
數組與其它容器之間的區別有三方面:效率,類型和保存基本類型的能力。
import java.util.*;
class Sphere{
private static long count;
private final long id=count++;
public String toString(){
return "Sphere "+id;
}
}
public class ContainerComparasion{
public static void main(String[] args){
Sphere[] s=new Sphere[10];
for(int i=0;i<5;i++)
s[i]=new Sphere();
System.out.println(Arrays.toString(s));
System.out.println(s[4]);
List<Sphere> sl=new ArrayList<Sphere>();
for(int i=0;i<5;i++)
sl.add(new Sphere());
System.out.println(sl);
System.out.println(sl.get(4));
int[] integers={0,1,2,3,4,5};
System.out.println(Arrays.toString(integers));
System.out.println(integers[4]);
List<Integer> li=new ArrayList<Integer>(Arrays.asList(0,1,2,3,4,5));
li.add(97);
System.out.println(li);
System.out.println(li.get(4));
}
}
需要注意的幾個地方:
1,可以將指向某個數組的引用賦值給另一個數組對象。
2,可以返回一個數組。
3,創建多維粗糙數組很方便。
Arrays實用功能:
equals():用於比較兩個數組是否相等
Arrays類提供了重載後的equals()方法,用來比較整個數組。
數組相等的條件是:元素個數必須相等,並且對應位置的元素也相等。
import java.util.*;
public class ComparingArrays{
public static void main(String[] args){
int[] a=new int[10];
int[] b=new int[10];
Arrays.fill(a,47);
Arrays.fill(b,47);
System.out.println(Arrays.equals(a,b));
b[3]=11;
System.out.println(Arrays.equals(a,b));
String[] c=new String[4];
Arrays.fill(c,"Hi");
String[] d={new String("Hi"),new String("Hi"),new String("Hi")};
System.out.println(Arrays.equals(c,d));
}
}
fill():用於填充數組
sort():用於對數組排序
String排序算法依據字典編排順序排序,所以大寫字母開頭的詞都放在前面輸出,然後纔是小寫字母開頭的詞。如果想忽略單詞字母的大小寫,可以使用String.CASE_INSENSITIVE_ORDER。
binarySearch():用於已經排好序的數組中查找元素
如果對未排序的數組使用binarySearch(),那麼將產生不可預料的結果。如果數組包含重複的元素,則無法保證找到的是這些副本中的哪一個。
toString():用於產生數組的String表示
hashCode():用於產生數組的散列碼
asList():用於接受任意的序列或者數組爲參數,並將其轉換成List容器
複製數組:
Java標準庫提供的static方法System.arraycopy(),用它賦值數組比用for循環賦值要快很多。System.arraycopy()針對所有類型做了重載。
import java.util.*;
public class CopyingArray{
public static void main(String[] args){
int[] i=new int[7];
int[] j=new int[10];
Arrays.fill(i,47);
Arrays.fill(j,103);
System.out.println("i= "+Arrays.toString(i));
System.out.println("j= "+Arrays.toString(j));
System.arraycopy(i,0,j,0,i.length);
System.out.println("j= "+Arrays.toString(j));
int[] k=new int[5];
Arrays.fill(k,103);
System.arraycopy(i,0,k,0,k.length);
System.out.println("k= "+Arrays.toString(k));
Arrays.fill(k,103);
System.arraycopy(k,0,i,0,k.length);
System.out.println("i= "+Arrays.toString(i));
//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.toString(u));
System.out.println("v= "+Arrays.toString(v));
System.arraycopy(v,0,u,u.length/2,v.length);
System.out.println("u= "+Arrays.toString(u));
}
}
arraycopy()需要的參數分別是:源數組,原數組中的什麼位置開始複製的偏移量,目標數組,目標數組中的什麼位置開始複製的偏移量,需要複製的元素的數量。
System.arraycop()不會執行自動包裝和自動拆包,兩個數組必須具有相同的確切類型。