gpt4 book ai didi

java - 避免以下未经检查的警告

转载 作者:行者123 更新时间:2023-11-30 09:54:18 25 4
gpt4 key购买 nike

我过去做了一些花哨的包装以避免未经检查的警告,但在仔细研究了 90 分钟后 http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html ,我无法在下面编写 findMatch 方法并使其在没有 @SuppressWarnings("unchecked") 的情况下工作。参数化类在编译时未知。

public interface Matchable<T>
{
public boolean matches(T toMatch);
}

public class PlaceForMatching
{
public static Object findMatch(Object toMatch, Object[] toSearch)
{
if(!(toMatch instanceof Matchable)) return null;

Matchable matchObj = (Matchable)toMatch;
Class<?> matchClass = matchObj.getClass();

for(Object obj : toSearch)
{
/**
* Check here verifies that the search list object we're about
* to check is the same class as the toMatch object.
* This means Matchable will work without a ClassCastException.
**/

if(matchClass.isInstance(obj) && matchObj.matches(obj))
return obj;
}
//Didn't find it
return null;
}
}

请注意代码有效,因为在每种情况下 Matchable 都是由 T 实现的。

Apple implements Matchable<Apple>
Orange implements Matchable<Orange>

编辑:添加一些测试代码

public static void main(String[] args)
{
Object[] randomList = createAppleArray();
Object apple = new Apple("Red");

Object match = findMatch(apple, randomList);
}

private static Object[] createAppleArray()
{
return new Object[] { new Apple("Pink"), new Apple("Red"), new Apple("Green") };
}


public class Apple implements Matchable<Apple>
{
String color;
public Apple(String color)
{
this.color = color;
}

public boolean matches(Apple apple)
{
return color.equals(apple.color);
}
}

最佳答案

public static <T extends Matchable<T>> T findMatch(T toMatch, T[] toSearch) {
if (toMatch == null)
return null;

Matchable<T> matchObj = toMatch;
Class<?> matchClass = matchObj.getClass();

for (T obj : toSearch) {
if (matchClass.isInstance(obj) && matchObj.matches(obj))
return obj;
}

return null;
}

关于java - 避免以下未经检查的警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3402569/

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