用Java写算法技巧(1)去掉List中的重复对象

    最近写聚类算法,输入的数据集是一些二维点坐标,我的数据有很多重复的点,需要做一下预处理,去掉这些重复点。百度和谷歌一阵后,找到了解决方法,希望对阅读本文的人有帮助。

   1、 数据文件points.txt,文件内容和格式如下:
   
           

   2、添加一个Point对象,用来保存点数据。最重要的是要实现equal方法,这个在去除重复对象时会用到。

public class Point {
	
    private double x;
    private double y;

    public double getX() {
      return x;
    }
    public void setX(double x) {
      this.x = x;
    }
    public double getY() {
      return y;
    }
    public void setY(double y) {
      this.y = y;
    }
    
    public Point(){
      x=0;
      y=0;
    }
    public Point(double x,double y){
      this.x=x;
      this.y=y;
    }
    public Point(String str){
      String[] p=str.split(",");
      this.x=Double.valueOf(p[0]);
      this.y=Double.valueOf(p[1]);
    }
    public String print(){
      return "<"+this.x+","+this.y+">";
    }
    
    //这个方法是关键
    public boolean equals(Object obj) {
		if (obj == null) {
			return false;
		}
		if (this == obj) {
			return true;
		}
		Point other = (Point) obj;
		if (this.getX() == other.getX() && this.getY() == other.getY()) {
			return true;
		}
		return false;
    }
}

3、从文件points.txt中读取点信息,然后保存在List对象中。

public List<Point> getPointsList() throws IOException{
      List<Point> lst=new ArrayList<Point>();
      String txtPath="points.txt";
      BufferedReader br=new BufferedReader(new FileReader(txtPath));
      String str="";
      while((str=br.readLine())!=null && str!=""){
        lst.add(new Point(str));
      }
      br.close();
      
      //过滤重复的Point对象
      List<Point> list = new ArrayList<Point>();
      for (Object o:lst)  
      {
    	  if (!list.contains(o))
    	  {
    		  list.add((Point)o);
    	  }
      }
      return list;
}



    

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值