有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!


共 (2) 个答案

  1. # 1 楼答案

    ^{}在这里很有用:

    public static <T> boolean hasDuplicates(List<T> list, T element) {
        return Collections.frequency(list, element) > 1;
    }
    

    这在时间上是线性的,所以在大型列表上可能会比较慢。但是,如果您需要使用List,那么您的性能不会更好,最多可以利用提前退出来减少平均运行时间:

    public static <T> boolean hasDuplicates(List<T> list, T element) {
        int count = 0;
        for (T other: list) {
            // Ugly, but necessary to ensure null-safety
            boolean areEquals = (other == null)? element == null : other.equals(element);
            if (areEquals) {
                count += 1;
                if (count > 1) {
                    return true;
                }
            }
        }
        return false;
    }
    
  2. # 2 楼答案

    要提高性能,您可以执行以下操作:

    1. 将列表转换为如下设置:

      Set<Employee> employeeSet = new HashSet<Employee>(employeeList);
      
    2. 现在,对于每个传入元素,您可以检查add方法返回的值是false还是true,如下所示:

      boolean bool = employeeSet .add(dupEmployee);
      if(bool)
         // do this
      else 
        // do that
      

    注意:您必须确保在Employee类中使用hashCodeequals方法