具有2个以上参数的java泛型

时间:2018-04-28 21:10:11

标签: java generics

我有一个课程测试,其中K,V,T - 键,值,时间戳 我有一个接口放置(K键,V值,T时间戳)

我对hashmap的初始化如下:

import java.util.*;
import java.lang.*;
import java.io.*;

class Test1<K,V,T> {

    private final HashMap<K, TreeMap<T, V>> map = new HashMap<K, TreeMap<T, V>>(); 
    private void put(K key, V value, T timeStamp) {

     }

    public void put(K key, V value){
         // Here it gives compiler error
        put(key, value, System.currentTimeMillis());
    }
}


/* Name of the class has to be "Main" only if the class is public. */
public class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        Test1<Integer, Integer, Long> classInstance = new Test1<>();
        classInstance.put(10, 10);
    }
}

但是这里给出了编译错误说明:

put(K,V,T)不适用于参数(Integer,Integer,Long)。

有人可以帮忙吗

1 个答案:

答案 0 :(得分:0)

我建议的解决方案是声明你的类是抽象的,这样你就可以留下子类来定义它们的时间戳是如何获得的:

public abstract class Test1<K,V,T> {

    private final HashMap<K, TreeMap<T, V>> map = new HashMap<>();

    private void put(K key, V value, T timeStamp) {
        // ...
    }

    public void put(K key, V value){
        // Here it no longer gives compiler error
        put(key, value, getCurrentTimestamp());
    }

    protected abstract T getCurrentTimestamp();
}

这允许T的任何引用类型,包括LongInteger或您可以想象的内容。任何想要使用该类的人都必须决定T 的类型以及生成类型T的适当对象的方法。这是我使用Instant个对象的示例:

class Test1UsingInstant extends Test1<Integer, Integer, Instant> {

    @Override
    // declared return type needs to the same as supplied
    // as third type in Test1<Integer, Integer, Instant> above
    protected Instant getCurrentTimestamp() {

        // returned value needs to be of the declared return type
        // (auto-boxing will work, though)
        return Instant.now();
    }

}

然后可以使用这个具体的子类,例如:

        Test1UsingInstant instance = new Test1UsingInstant();
        instance.put(10, 10);

对双参数put的调用进入Test1类,其中getCurrentTimestamp被调用以获得Instant,而put又作为第三个提供参数为三参数public class Test1UsingLong extends Test1<Integer, Integer, Long> { @Override protected Long getCurrentTimestamp() { return System.currentTimeMillis(); } }

另一个例子:

        Test1UsingLong instance = new Test1UsingLong();
        instance.put(10, 10);

以与第一个示例相同的方式使用:

getCurrentTimestamp

我编译并运行了所有代码。

对于时间戳,

Put()也可称为工厂方法。换句话说,我使用的是Factory Method design pattern

相关问题