据我所知,完整的解决方案
- 每个类层次结构的BFS都是“向上”的-生成linkedHashSet(保留顺序+无重复)
- 将每个集合与下一个相交以找到任何共同点,再次使用linkedHashSet保留顺序
- 其余的“有序”集合是共同祖先,列表中的第一个是“最近的”,最后一个是最远的。
- 空列表意味着没有祖先(对象除外)
码
private static Set<Class<?>> getClassesBfs(Class<?> clazz) { Set<Class<?>> classes = new linkedHashSet<Class<?>>(); Set<Class<?>> nextLevel = new linkedHashSet<Class<?>>(); nextLevel.add(clazz); do { classes.addAll(nextLevel); Set<Class<?>> thisLevel = new linkedHashSet<Class<?>>(nextLevel); nextLevel.clear(); for (Class<?> each : thisLevel) { Class<?> superClass = each.getSuperclass(); if (superClass != null && superClass != Object.class) { nextLevel.add(superClass); } for (Class<?> eachInt : each.getInterfaces()) { nextLevel.add(eachInt); } } } while (!nextLevel.isEmpty()); return classes;}private static List<Class<?>> commonSuperClass(Class<?>... classes) { // start off with set from first hierarchy Set<Class<?>> rollingIntersect = new linkedHashSet<Class<?>>( getClassesBfs(classes[0])); // intersect with next for (int i = 1; i < classes.length; i++) { rollingIntersect.retainAll(getClassesBfs(classes[i])); } return new linkedList<Class<?>>(rollingIntersect);}
配套方法及试验
private static void test(Class<?>... classes) { System.out.println("Common ancestor for " + simpleClassList(Arrays.asList(classes)) + ", Result => " + simpleClassList(commonSuperClass(classes)));}private static String simpleClassList(Collection<Class<?>> classes) { StringBuilder builder = new StringBuilder(); for (Class<?> clazz : classes) { builder.append(clazz.getSimpleName()); builder.append(","); } return builder.toString();}public static void main(String[] args) { test(A.class, AImpl.class); test(A.class, B.class, C.class); test(A.class, AB.class); test(AImpl.class, ABImpl.class); test(ABImpl.class, ABImpl2.class); test(AImpl.class, ABImpl.class, ABImpl2.class); test(ABImpl.class, ABImpl2.class, BCImpl.class); test(AImpl.class, ABImpl.class, ABImpl2.class, BCImpl.class); test(AB.class, ABImpl.class);}
输出量
Common ancestor for A,AImpl,, Result => A,Common ancestor for A,B,C,, Result => Common ancestor for A,AB,, Result => A,Common ancestor for AImpl,ABImpl,, Result => A,Common ancestor for ABImpl,ABImpl2,, Result => A,B,Common ancestor for AImpl,ABImpl,ABImpl2,, Result => A,Common ancestor for ABImpl,ABImpl2,BCImpl,, Result => B,Common ancestor for AImpl,ABImpl,ABImpl2,BCImpl,, Result => Common ancestor for AB,ABImpl,, Result => AB,A,B,
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)