为Java的containsKey操作计算纳秒时间

问题描述

我正在尝试创建一个代码,该代码将以十亿分之一秒为单位计算Java Map的containsKey-运算(例如其运行该运算的速度)。方法具有 Map D 作为参数,并且返回的值应为containsKey操作正常使用的时间,以纳秒为单位。我真的不知道如何继续下去。 Netbeans IDE给出错误消息,提示我这里存在某种无限循环。

到目前为止,这是我的代码

import java.util.*;


public class calculateNanotime implements calculateNanotime{

   /* 
     * Measures Map's containsKey -operaation's time frequency as nanoseconds.
     * @param D Map to be tested
     * @return containsKey -operation's duration as nanoseconds
     */

    //@Override
    public long containsKeyTime(Map<Double,Double> D) {

        // I should try with different key values
        D.containsKey(1.0);
     
        long beginning = System.nanoTime();
        long end = System.nanoTime();
        
        long result = end - beginning;
    
 //I have a code in another class of this package,which will be testing how well this code work,after this is ready
        result = testable.containsKeyTime(D);
          return result;
}
}

以下是错误消息: 线程“主”中的异常java.lang.StackOverflowError 在calculateNanotime.calculateNanotime.containsKeyTime(calculateNanotime.java:35)

在calculateNanotime.calculateNanotime.containsKeyTime(calculateNanotime.java:42)

解决方法

您的无限循环错误很可能来自此

public class calculateNanotime implements calculateNanotime

其中有一个实现相同名称的接口的类。

请参见Java Class and Interface Name Collision

,

您没有无限循环,您拥有的是递归函数,没有终止的基本情况。您的containsKeyTime方法可能应该将要检查映射是否包含为键的值作为参数。也许像:

public class calculateNanotime implements calculateNanotime {    
    @Override
    public long containsKeyTime(Map<Double,Double> doubleMap,double value) {     
        long beginning = System.nanoTime();
        boolean result = doubleMap.containsKey(value); //what to do with result?
        return System.nanoTime() - beginning;
    }
}