java 泛型参数传递_Java泛型传递参数

博客讨论了在Java中使用泛型和接口时遇到的问题。作者尝试创建一个方法`myMethod`,确保传入的Map的键类型与`MyInterface`中参数的类型一致。然而,由于类型参数的限制,导致无法将不同类型的键(如`Object.class`和`String.class`)与对应的`MyInterface`实现一起放入Map中。文章展示了尝试的代码片段和遇到的编译错误。
摘要由CSDN通过智能技术生成

希望有人可以帮助我摆脱这种困扰.

我做了这个方法:

public static void myMethod(Map,MyInterface> map) {

}

使用参数T以确保用作键的类与用作MyInterface中的参数的类相同.

现在我想传递一个不同类作为键的映射,当然还有MyInterface的相应实现.

但它不起作用,因类型参数而导致语法错误.这是代码,我希望是自我解释.

import java.util.HashMap;

import java.util.Map;

public class Test {

public static void main(String[] args) {

Map,MyInterface>> map = new HashMap,MyInterface>>();

// Map,MyInterface> map = new HashMap,MyInterface>();

map.put(Object.class,new MyObjectImpl());

//if I use Map,MyInterface> I get a compiler error here

//because map is not map basically

map.put(String.class,new MyStringImpl());

//this would be possible using >,which is exactly what I don't want

// map.put(String.class,new MyIntegerImpl());

//> generates anyways a compiler error

myMethod(map);

}

//use T to make sure the class used as key is the same as the class of the parameter "object" in doSomething

public static void myMethod(Map,MyInterface> map) {

}

interface MyInterface {

void doSomething(T object);

}

static class MyObjectImpl implements MyInterface {

@Override

public void doSomething(Object object) {

System.out.println("MyObjectImpl doSomething");

}

}

static class MyStringImpl implements MyInterface {

@Override

public void doSomething(String object) {

System.out.println("MyStringImpl doSomething");

}

}

static class MyIntegerImpl implements MyInterface {

@Override

public void doSomething(Integer object) {

System.out.println("MyIntegerImpl doSomething");

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值