如何检查2个实例(一个未知)的参数是否相同

时间:2016-03-02 23:46:01

标签: java constructor exists

我已经检查了类似的问题,但没有人真正回答我的问题。 我可能有多个Tile实例,如果已经有一个具有相同Coordinate2D的对象Tile,我必须检查每个新构造。 Coordinate2D由(int x,int y)组成。 我的问题是,当我使用已知的Coordinate2D创建Tile时,我如何找出是否已经存在具有相同对象Coordinate2D作为参数的Tile,以便我可以抛出TileExistsException?

    public Tile(Coordinate2D coord, int value)throws TileExistsException {      

      this.coord = coord;
      this.value = value;
    }

1 个答案:

答案 0 :(得分:0)

保留一组到目前为止使用的所有参数值,并在构造函数中检查它。它必须是static,因此所有实例共享相同的数据。

private static Set<Coordinate2D> coordinates = new HashSet<>();

public Tile(Coordinate2D coord, int value) throws TileExistsException {
    if (!coordinates.add(coord)) {
        throw new TileExistsException();
    }
    this.coord = coord;
    this.value = value;
}

Set true方法返回false如果操作更改了集合,那么如果已经使用了坐标,它将返回HashSet

注意

要使Coordinate2D生效,您的hashCode()课程必须根据标识该实例的字段实施equals()x,我认为该y public class Coordinate2D { int x; int y; public boolean equals(Object o) { return o instanceof Coordinate2D && ((Coordinate2D)o).x == x &&((Coordinate2D)o).y == y; } public int hashCode() { return Objects.hash(x, y); } // other methods and fields } }和// file meteor.d.ts declare module "meteor/meteor" { export module Meteor { ... } } // file context.d.ts // not part of any module declare interface IContext { Meteor: typeof Meteor; // how do I get the referwence to Meteor? } ,例如:

server {
    listen   80;
    listen   [::]:80;
    listen 443 default ssl;
    server_name marketplace_unirgy;
    ssl_certificate /etc/nginx/ssl/nginx.crt;
    ssl_certificate_key /etc/nginx/ssl/nginx.key;
    root /var/www/html/marketplace_unirgy/;
    index index.php;
    #location / {
    #       index index.html index.php;
    #       autoindex on;
    #       #If missing pass the URI to Magento's front handler
    #       try_files $uri $uri/ @handler;
    #       expires max;
    #}
    #need it to execute php
    location ~ \.php$ {
            fastcgi_pass unix:/var/run/php5-fpm.sock;
            include fastcgi_params;
            include fastcgi.conf;
    }
    ## Magento uses a common front handler
    location @handler {
            rewrite / /index.php;
    }
}