What is “Type mismatch” and how do I fix it?

浪子不回头ぞ 提交于 2019-12-08 09:56:39

问题


How to fix this error?

Type mismatch: cannot convert from element type Object to Block

I see it at this line:

for (Block b : blocksToSkip){

Here is the full code.

@EventHandler(priority=EventPriority.NORMAL, ignoreCancelled=true)
public void onEntityExplode(EntityExplodeEvent ev){
    ArrayList blocksToSkip = new ArrayList();
    Location rootLoc = ev.getLocation();
    if (!SkyMagic.IsInIslandWorld(rootLoc)) return;
    for (Block b : ev.blockList()){
        Location loc = b.getLocation();
        IslandData data = SkyMagic.GetIslandAt(loc);
        if ((data != null) && (data.owner != null)){
            blocksToSkip.add(b);
        }
    }
    for (Block b : blocksToSkip){
        ev.blockList().remove(b);
    }
}

回答1:


This is a raw type:

ArrayList blocksToSkip

Java expects everything, not only the Block type. Therefore, you need a type cast.

ArrayList blocksToSkip = new ArrayList();

// Rest of your code

for (Object b : blocksToSkip){
    ev.blockList().remove( (Block)b );
}

Note it is discouraged to use raw types. You should parameterize instead.

ArrayList<Block> blocksToSkip = new ArrayList<Block>();


来源:https://stackoverflow.com/questions/27325278/what-is-type-mismatch-and-how-do-i-fix-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!