【问题标题】:How test URI for equals without parameter order?如何在没有参数顺序的情况下测试等于的 URI?
【发布时间】:2015-10-26 05:07:15
【问题描述】:

考虑一个代码:

URI one = URI.create("http://localhost:8081/contextRoot/main.html?one=1&second=2");
URI second = URI.create("http://localhost:8081/contextRoot/main.html?second=2&one=1");
System.out.println(one.equals(second));

它会打印出false。有没有办法在没有 URI 参数顺序的情况下测试 URI?

【问题讨论】:

  • @TimBiegeleisen 如何为 Java 运行时定义的类覆盖 equals()?我不确定你想说什么。
  • @ajb 选词错误,抱歉 :-|
  • 我没有完整的答案。我将提取查询部分,然后对于每个 URI,在 "&" 上使用 split 创建一个参数数组,然后从每个参数数组创建一个 Set<String>,然后比较集合是否相等。您必须比较 URI 的其他部分,或者通过 copmaring 每个部分,或者通过创建没有查询部分的新 URI 并在这些部分上使用 equals()。我不知道最后一个是否可行。
  • @ajb 在他澄清之前不要发布答案,但是是的,这种方法似乎很合理。
  • @ajb - 是的,这可能不是最干净的方法。但它会起作用。我想知道是否有这样做的图书馆

标签: java uri


【解决方案1】:

不幸的是,URI/URL 对象的 equals 方法并不总是有效,这正是您所期待的。这就是为什么要比较具有不同参数顺序的 2 个 URI(如果您认为,顺序对您来说并不重要),您应该使用一些实用程序逻辑。例如如下:

public static void main(String... args) {
    URI one = URI.create("http://localhost:8081/contextRoot/main.html?one=1&second=2");
    URI second = URI.create("http://localhost:8081/contextRoot/main.html?second=2&one=1");
    System.out.println(one.equals(second));
    System.out.println(areEquals(one, second));
}

private static boolean areEquals(URI url1, URI url2) {
    //compare the commons part of URI
    if (!url1.getScheme().equals(url1.getScheme()) ||
            !url1.getAuthority().equals(url2.getAuthority()) ||
            url1.getPort() != url2.getPort() ||
            !url1.getHost().equals(url2.getHost())) {
        return false;
    }

    //extract query parameters
    String params1 = url1.getQuery();
    String params2 = url2.getQuery();

    if ((params1 != null && params2 != null) && (params1.length() == params2.length())) {
        //get sorted list of parameters
        List<String> list1 = extractParameters(params1);
        List<String> list2 = extractParameters(params2);

        //since list are sorted and contain String objects, 
        //we can compare the lists objects
        return list1.equals(list2);
    } else {
        return false;
    }
}

//return sorted list of parameters with the values
private static List<String> extractParameters(String paramsString) {
    List<String> parameters = new ArrayList<>();

    String[] paramAr = paramsString.split("&");
    for (String parameter : paramAr) {
        parameters.add(parameter);
    }
    Collections.sort(parameters);
    return parameters;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-15
    • 1970-01-01
    • 2014-11-17
    相关资源
    最近更新 更多