您的位置:首页 > 其它

重写对象equals和compareTo方法

2017-09-18 23:20 302 查看
package day02;

/**

 * 使用该类重写Object相关方法

 * @author soft01

 *

 */

public class Point {

private int x;

private int y;

public Point(int x, int y) {

 super();

 this.x = x;

 this.y = y;

}

public int getX() {

 return x;

}

public void setX(int x) {

 this.x = x;

}

public int getY() {

 return y;

}

public void setY(int y) {

 this.y = y;



/**

 * 重写toString

 * toString方法的意义是当前对象以一个

 * 字符串形式表达

 *

 */

public String toString(){

 return "("+ x +","+ y +")";

   

}

/*+

 * equals  方法的作用是比较两个对象的、

 * 内容是否一致

 *比较的是两个对象的属性值是否相同

 *但是并不要求必须所有属性值都一致

 *这个要结合实际需求而定

 */

public boolean equals(Object o){

 if(o==null){

  return false;

 }

 if(o==this){

  return true;

 }

 if(o instanceof Point){

  Point p=(Point)o;

  return this.x==p.x&&this.y==p.y;

 }

 return false;

}

}

package day02;
public class TestToStringDemo {
 public static void main(String[] args) {

  Point p=new Point(1,2);

  /*

   * Object定义了toString方法,返回的

   * 字符串是该对象的句柄

   * 句柄:类名@地址 就是对象的引用信息

   * 实际对开发没有什么帮助,所以当我们

   * 需要使用一个对象的toString方法时,

   * 应当重写该方法

   */

     String str=p.toString();

       System.out.println(str);

     

        /* System.out.println(object o)

        * 该方法会将给定对象toString返回的

        * 字符串输出到控制台

        */

         System.out.println(p);

      

        

     Point p2=new Point(1,2);

         System.out.println(p==p2);

         System.out.println(p.equals(p2));

         /*

          * Object的equals方法就是使用“==="

          * 比较的,所以若希望判断两个对象的意义是否相等

          *

          */

      

 }
}

重写compareTof方法
package day05;
public class Point implements Comparable<Point>{

 private int x;

 private int y;

 public Point(int x, int y) {

  super();

  this.x = x;

  this.y = y;

 }

 public int getX() {

  return x;

 }

 public void setX(int x) {

  this.x = x;

 }

 public int getY() {

  return y;

 }

 public void setY(int y) {

  this.y = y;

 }

 @Override

 /*

  * 该方法的作用是当前对象this与参数o比较大小

  * 具体是几并不重要

  * 当返回值>0,this>o

  * 当返回值=0,this==o

  * 当返回值<0,this<o

  */

 public String toString (){

  return x+" "+y;

 }

 public int compareTo(Point p) {

  int len=this.x*this.x+this.y*this.y;

  int len1=p.x+p.x+p.y*p.y;

  return len-len1;

 }
}

package day05;
import java.util.ArrayList;

import java.util.Collections;

import java.util.List;
public class SortListDemo1 {
 public static void main(String[] args) {

  List<Point> list=new ArrayList<Point>();

  list.add( new Point(2,3));

  list.add( new Point(3,4));

  list.add( new Point(5,6));

  list.add( new Point(4,5));

  System.out.println(list);

  Collections.sort(list);

  System.out.println(list);

 }
}

//
[2 3, 3 4, 5 6, 4 5]

[2 3, 3 4, 4 5, 5 6]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  对象
相关文章推荐