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