2012-09-02 195 views
2

我确实有int对集合,即; (int,int)集合集合中的唯一集合

1)给定k个这样的对,检查它们是否唯一。即;使用k对形成的集合的大小是k? 2)如果给定的k个记录是唯一的,则按排序顺序(按x和y解决冲突)存储它们。3)给定n个这样的k组,

的要求1实施例和图2
如果k = 3

(100,100)(110,300)(120,200)是一组有效的和以排序的顺序。 (100,100)(300,200)(200,300)是有效集合,但不是按排序顺序。
(100,100)(100,200)(100,200)是在有效集的要求3
输入

实施例:

(100,100)(200,300 )(300,200)
(100,100)(200,300)(300,200)
(100,100)(201,300)(300,200)

输出:

(100,100)(200,300)(300,200)
(100,100)(201,300)(300,200)

这是最接近类似于我正面临着真正的问题。我需要用Java完成这项工作,而且我从未在java中工作过。我是一名中级C++程序员。

我可以解决1和2通过一些丑陋的编码和排序。
但是我不能够得到3.下面是我能得到迄今3类对实现可比

(POC代码)

import java.util.HashSet; 
public class set { 
    public static void main (String []args) { 
     HashSet<Pair> s1 = new HashSet(); 
     s1.add(new Pair(10,10)); 
     s1.add(new Pair(10,10)); 

     HashSet<Pair> s2 = new HashSet(); 
     s2.add(new Pair(10,10)); 
     s2.add(new Pair(10,10)); 

     HashSet<HashSet<Pair>> s12 = new HashSet(); 
     s12.add(s1);s12.add(s2); 
     for (HashSet<Pair> hs : s12) { 
      for (Pair p : hs) { 
       System.out.println(""+ p.toString()); 
      } 
     } 
    } 
} 
+3

这是一门功课? –

+0

是和否 我开始通过作业问题探索计算几何算法。在移动行扫描和其他算法之前,我想自己试一试 http://en.wikipedia.org/wiki/Line_segment_intersection –

+0

HashSet代码的HashSet究竟有什么错误?它看起来不错,给予或采取一些未经检查的操作。 –

回答

2

看起来你没有重载equals和/或配对类中的hashCode方法。

例如,如果你Pair类具有以下结构:

protected K value1; 
protected V value2; 

你应该实现equalshashCode为(例如):

public boolean equals(Object obj) { 
    if (!(obj instanceof Pair)) 
     return false; 
    Pair that = (Pair)obj; 
    boolean result = true; 
    if (this.getValue1() != null) 
     result = this.getValue1().equals(that.getValue1()); 
    else if (that.getValue1() != null) 
     result = that.getValue1().equals(this.getValue1()); 

    if (this.getValue2() != null) 
     result = result && this.getValue2().equals(that.getValue2()); 
    else if (that.getValue2() != null) 
     result = result && that.getValue2().equals(this.getValue2()); 

    return result; 
} 


public int hashCode() { 
    int result = value1 != null ? value1.hashCode() : 0; 
    result = 31 * result + (value2 != null ? value2.hashCode() : 0); 
    return result; 
} 
+0

看起来像这是我失踪。但总的来说,是否有更好的方法来处理问题? –

+0

我认为更好的方法是使用TreeSet而不是HashSet,因为您希望按排序顺序存储对象对象。无论如何你必须实现equals和hashCode .. –