package untitled4;
import java.util.*;
class compare implements Comparator
{
public int compare(Object o1,Object o2)
{
int i=((Person)o1).getFirstName().compareTo(((Person)o2).getFirstName());
return (i!=0?i:((Person)o1).getLastName().compareTo(((Person)o2).getLastName()));
}
}
class Person implements Comparable
{ private String firstName;
private String lastName;
public String getFirstName()
{
return firstName;
}
public String getLastName()
{ return lastName;
}
public Person(String f,String l)
{
firstName=f;
lastName=l;
}
public int compareTo(Object o)
{ Person p=(Person)o;
int l=firstName.compareTo(p.firstName);
return (l!=0?l:(lastName.compareTo(p.lastName)));
}
public String toString()
{
return firstName+" "+lastName;
}
}
public class ArrayTest {
public ArrayTest() {
}
public static void main(String args[])
{
int a[];
a = new int[5];
Arrays.fill(a, 5); //用5填充數組
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
int b[] = {10, 3, 5, 6, 8, 9};
Arrays.sort(b);
for (int i = 0; i < b.length; i++) {
System.out.println(b[i]);
}
Person p[] = {
new Person("John", "Lennon"),
new Person("Karl", "Marx"),
new Person("Groucho", "Marx"),
new Person("Oscar", "Grouch")
};
for (int i = 0; i < p.length; i++) {
System.out.println(p[i]);
}
//Arrays.sort(p);
Arrays.sort(p, new compare());
for (int i = 0; i < p.length; i++) {
System.out.println(p[i]);
}
int s = Arrays.binarySearch(p, new Person("Groucho", "Marx"), new compare());
System.out.println(s);
Person person[];
person = new Person[4];
System.arraycopy(p, 0, person, 0, p.length);
for (int c= 0; c < person.length; c++)
{
System.out.println(person[c]);
}
}
}
當用Arrays的sort方法時,需要排序的數組必須實現Comparable借口.或者實現Comparator接口
Arrays的fill方法是用一個基本類型或者一個對象填充數組.
當調用binarySearch()時如果是調用sort(Objiec a[],Comparator a)時,,應調用相應的binarySearch(Object a[],Object value,Comparator)方法.
equals()方法用于比較非基本類型數組時,調用他們的equals方法..比如
int a[]={5,4,3,2,1};
int c[]={5,4,3,2,1}; 基本類型比較他們的值,
System.out.println(Arrays.equals(a,c)); TRUE
Integer a[]={new Integer(1),new Integer(2),new Integer(3)};
Integer b[]={new Integer(1),new Integer(2),new Integer(3)};
System.out.println(Arrays.equals(a,b)); 調用Integer.equals()方法
對于沒有覆蓋Object equals方法的對象數組,他們之間比較的是對象的引用.
System.arraycopy()方法對與基本類型來說只是復制他們的值.而對于非基本類型時他們復制引用
person person[]={new person("guo",20),new person("cher",21)};
person per[]={new person("guo",20),new person("cher",21)};
person []p=new person[2];
System.arraycopy(person,0,p,0,person.length);
System.out.println(person==p); //輸出 false
person[1].setName("hao");
System.out.println(person[1].equals(p[1])); 輸出 true
System.out.println(Arrays.equals(person,p)); 輸出 true
System.out.println(Arrays.equals(person,per)); 輸出 false