Java ArrayList的equals方法

在调用ArrayList的equals方法时,不太确定是怎么执行的,做了一个小实验。如下:

新建实体类VM,重写hashcode和equals方法:

public class VM {
	
	public int id;
	
	public int mem;
	public int cpu;
	
	/**VM所在的host*/
	public Host host;

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + cpu;
		result = prime * result + ((host == null) ? 0 : host.hashCode());
		result = prime * result + id;
		result = prime * result + mem;
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		
		System.out.println("call equals");
		
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		VM other = (VM) obj;
		if (cpu != other.cpu)
			return false;
		if (host == null) {
			if (other.host != null)
				return false;
		} else if (!host.equals(other.host))
			return false;
		if (id != other.id)
			return false;
		if (mem != other.mem)
			return false;
		return true;
	}
}

测试函数如下:

import java.util.ArrayList;

import model.VM;


public class Test {

	public static void main(String[] args) {
		
		ArrayList<VM> a1 = new ArrayList<VM>();
		VM vm1 = new VM(1024,2);
		vm1.id = 1;
		a1.add(vm1);
		
		ArrayList<VM> a2 = new ArrayList<VM>();
		VM vm2 = new VM(1024,2);
		vm2.id = 2;
		a2.add(vm2);
		
		System.out.println(a1.equals(a2));
	}

}

结论为在调用ArrayList的equals方法时,调用了ArrayList元素的各个equals方法。具体实现如下:
    public boolean equals(Object o) {
        if (o == this)
            return true;
        if (!(o instanceof List))
            return false;

        ListIterator<E> e1 = listIterator();
        ListIterator e2 = ((List) o).listIterator();
        while (e1.hasNext() && e2.hasNext()) {
            E o1 = e1.next();
            Object o2 = e2.next();
            if (!(o1==null ? o2==null : o1.equals(o2)))
                return false;
        }
        return !(e1.hasNext() || e2.hasNext());
    }


你可能感兴趣的:(Java ArrayList的equals方法)