gpt4 book ai didi

java - 如何使用泛型来处理具有公共(public)父类(super class)及其集合的不同类的对象的定义操作而不进行强制转换?

转载 作者:行者123 更新时间:2023-12-01 09:32:33 25 4
gpt4 key购买 nike

让我们拥有父类(super class)ProxyHost和扩展类HttpProxyHostHttpsProxyHostsSocks4ProxyHostSocks5ProxyHost

让我们对这些具体类进行一些集合:

private ArrayList<HttpsProxyHost> httpsProxies = new ArrayList<>();
private ArrayList<Socks5ProxyHost> socks5Proxies = new ArrayList<>();
private ArrayList<HttpProxyHost> httpProxies = new ArrayList<>();
private ArrayList<Socks4ProxyHost> socks4Proxies = new ArrayList<>();

现在我想做的是做类似的事情(下面有两个变体,都失败了):

    private <T extends ProxyHost> void processRow(Element row, T h, ArrayList<T> httpProxies) {
h.setIp("someIp");
h.setOrigin("Some origin");
h.setPort(1234);
httpProxies.add(h);
}

//some other part of app:
ArrayList<? super ProxyHost> list;
ProxyHost proxy;
switch (type) {
case "HTTP":
proxy = new HttpProxyHost();
processRow(row,proxy,httpProxies); // argument missmatch
break;
case "HTTPS":
proxy = new HttpsProxyHost();
processRow(row,proxy,httpsProxies); //argument missmatch
break;
case "SOCKS4":
list = socks4Proxies; //lists type mismatch
proxy = new Socks4ProxyHost();
break;
case "SOCKS5":
list = socks5Proxies; //lists type mismatch
proxy = new Socks5ProxyHost();
break;
}

所以问题是,为了在添加到具体集合之前保持该代码段干燥,我想执行一些常见操作。如何使用泛型而不使用父类(super class)型和显式转换来做到这一点?有办法吗?

每次我以为我理解了通用集合,不久之后我发现我实际上不理解;(

编辑:我想出了目前能想到的最优雅的解决方案:

private <T extends ProxyHost> void processRow(Element row, T h, List<T> list) {
h.setIp(row.child(0).text());
h.setPort(Integer.parseInt(row.child(1).text()));
h.setOrigin("SomeOrigin");
list.add(h);
}
//and calls:
processRow(row, new HttpProxyHost(), httpProxies);
processRow(row, new HttpsProxyHost(), httpsProxies);
//etc works like charm now

最佳答案

为了processRow(row,proxy,httpProxies)上类,T必须解析为 HttpProxyHost ,否则参数ArrayList<T> httpProxies将与 httpProxies 不兼容类型值ArrayList<HttpProxyHost> .

但是,如果 THttpProxyHost ,然后参数T h需要 HttpProxyHost ,但该值给出为 proxy类型 ProxyHost ,即使它实际上拥有 HttpProxyHost 类型的对象.

通过分配new HttpProxyHost()ProxyHost proxy ,您失去了调用工作所需的兼容性。

您需要:

case "HTTP": {
HttpProxyHost httpProxy = new HttpProxyHost();
processRow(row, httpProxy, httpProxies);
proxy = httpProxy;
break;
}

关于java - 如何使用泛型来处理具有公共(public)父类(super class)及其集合的不同类的对象的定义操作而不进行强制转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39288511/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com