简体   繁体   中英

How can java function adopt various parameter types by template or something else?

I tried to implement a function adaptive to different Buffer types, such as ByteBuffer, IntBuffer, FloatBuffer and etc. The pseudo code was show as followed

<T1, T2> boolean compareBuffer(T1 buf1, T1 buf2) {
    if(buf1.capacity() != buf2.capacity()) {
        return false;
    }
    for(int i = 0; i < buf1.capacity(); i++) {
        T2 v1 = buf1.get(i);
        T2 v2 = buf2.get(i);
        if(v1 != v2) {
            return false;
        }
    }
    return true;
}

The compiler reported errors. How can I do this in a simple way?

You need to understand about type erasure in Java.

In your case, the compiler has no information about the types T1 and T2, except that they must be descendants of Object, because all reference types are. Thus you can only use attributes and methods of Object in the body of compareBuffer.

It appears you expect T1 and T2 to implement the Buffer interface. Therefore declare:

  <T1 extends Buffer, T2 extends Buffer> boolean compareBuffer(T1 buf1, T1 buf2) 

Now you can use attributes and methods of Buffer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM