论坛首页 Java企业应用论坛

EqualsBuilder典型示例

浏览 2575 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2008-07-08  
OO

1.判断是否为空(null),是则false

2.判断是否为同一类型(instanceof),否则false

3.判断是否为同一对象(==),是则true,否则执行EqualsBuilder   


package com.iwindyforest.eb;

import org.apache.commons.lang.builder.EqualsBuilder;

public class User
{
    int id;
    String name;
    String sex;
    int age;
    String address;

    public User(int id, String name, String sex, int age, String address)
    {
        this.id = id;
        this.name = name;
        this.sex = sex;
        this.age = age;
        this.address = address;
    }

    public int getId()
    {
        return id;
    }

    public void setId(int id)
    {
        this.id = id;
    }

    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }

    public String getSex()
    {
        return sex;
    }

    public void setSex(String sex)
    {
        this.sex = sex;
    }



    public int getAge()
    {
        return age;
    }



    public void setAge(int age)
    {
        this.age = age;
    }



    public String getAddress()
    {
        return address;
    }



    public void setAddress(String address)
    {
        this.address = address;
    }



    public boolean equals(User user)
    {
        if(user == null)
        {
            return false;
        }

        if(!(user instanceof User))
        {
            return false;
        }

        if(this == user)
        {
            return true;
        }
        else
        {
            return new EqualsBuilder()
                         .append(this.getId(), user.getId())
                         .append(this.getAddress(), user.getAddress())
                         .append(this.getAge(), user.getAge())
                         .append(this.getName(), user.getName())
                         .append(this.getSex(), user.getSex)).isEquals();
        }
    }
}

   


package com.iwindyforest.eb;

public class EqualsBuilderTest
{
    User a, b;

    public EqualsBuilderTest()
    {

        a = new User(1, "cyh", "male", 20, "shangdi haidian beijing");
        b = new User(1, "cyh", "male", 20, "shangdi haidian beijing");
        System.out.println(a.equals(null));
        System.out.println(a.equals(new User(2, "cyh", "male", 20,
        "shangdi haidian beijing")));
        System.out.println(a.equals(b));
    }

    public static void main(String[] args)
    {
       new EqualsBuilderTest();
    }
}



  • EqualsBuilder.rar (225.1 KB)
  • 描述: EqualsBuilder典型示例 源代码
  • 下载次数: 68
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics