类型安全:通过可变参数子树潜在的堆污染 [英] Type safety: Potential heap pollution via varargs parameter subtrees

查看:35
本文介绍了类型安全:通过可变参数子树潜在的堆污染的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读 J. Bloch 的有效 Java 并且我了解到未经检查的强制转换永远不会好,除非我们确保强制转换是安全的.现在,由于 Java Collection 框架没有为我们提供 Tree 数据结构,我必须自己编写.

I'm reading J. Bloch's effective Java and I got that unchecked casts is never good unless we made sure that the cast is safe. Now, since Java Collection frameworks doesn't provide us with Tree data structure I have to write on my own.

public interface TreeVisitor<E, R> {
    public R visit(E leaf);

    public R visit(E val, Tree<E>... subtrees);
}

public abstract class Tree<E> {

    public abstract <R> R accept(TreeVisitor<E, R> visitor);

    public Tree<E> leaf(E leaf) {
        return new Tree<E>() {
            @Override
            public <R> R accept(TreeVisitor<E, R> visitor) {
                return visitor.visit(leaf);
            }
        };
    }

    public Tree<E> branch(E value, Tree<E>... subtrees){ //1
        return new Tree<E>(){
            @Override
            public <R> R accept(TreeVisitor<E, R> visitor) {
                return visitor.visit(value, subtrees);
            }
        };
    }

}

//1,我收到警告:

类型安全:通过可变参数子树的潜在堆污染

Type safety: Potential heap pollution via varargs parameter subtrees

如何检查我的代码是否真的安全?

How can I check that my code actually safe?

推荐答案

如何检查我的代码是否真的安全?

How can I check that my code actually safe?

如果访问者只依赖subtrees的元素是Tree,而不依赖subtreesTree[].如果是这种情况,那么您应该使用 @SafeVarargs 注释 visit 方法.

It's safe if the visitors only rely on the fact that the elements of subtrees are Tree<E>, and do not rely on the fact that subtrees is Tree<E>[]. If that is the case, then you should annotate the visit method with @SafeVarargs.

这篇关于类型安全:通过可变参数子树潜在的堆污染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆