检查数组是否为空时发生NullPointerException

时间:2014-11-08 04:39:20

标签: java arrays nullpointerexception bukkit

当我检查数组的长度是否等于0时,我得到NullPointerException,我无法找到它为什么不起作用。谁能告诉我我做错了什么? 这是我的整个功能代码:

    public static ArrayList<String> searchZone(Player p){
    openConnection();
    ArrayList<String> data = new ArrayList<String>();
    WorldEditPlugin worldEdit = (WorldEditPlugin) Bukkit.getServer().getPluginManager().getPlugin("WorldEdit");
    Selection selection = worldEdit.getSelection(p);
    String query = "SELECT * FROM " + db + ".blocks";
    ArrayList<String> res = executeQueryWe(query);
    String[] items = res.toArray(new String[res.size()]);
    int i = 0;
    int iters = items.length;
    while(i < iters){
        try{
        if(selection != null){
            String[] locs = items[i].split(",");
            World world = Bukkit.getServer().getWorld(locs[0]);
            int x = Integer.valueOf(locs[1]);
            int y = Integer.valueOf(locs[2]);
            int z = Integer.valueOf(locs[3]);
            Location loc = new Location(world, x, y ,z);
            if(selection.contains(loc)){

                String query2 = "SELECT * FROM `blocks` WHERE `world`='" + world.getName() + "' AND `x`='" + x + "' AND `y`='" + y + "' AND `z`='" + z + "';";
                data = executeQuery(query2);
            }
        }
        } catch(Exception e){
            closeConnection();
            p.sendMessage(prefix + ChatColor.RED + "An error occured while reading database");
            break;
        }
        p.sendMessage(prefix + ChatColor.RED + "Please make a selection first");
        break;
    }
    if(data.size() != 0){ //<---------------------------- ERROR COMES FROM HERE
        closeConnection();
        return data;
    } else {
        data.add("No entries has been found.");
        closeConnection();
        return data;
    }
}

2 个答案:

答案 0 :(得分:2)

您收到NullPointerException,因为如果该位置没有匹配的记录,executeQuery(query2)可能会返回null

要解决的一种方法是,检查null然后size

data != null && !data.isEmpty()

这与您的代码功能相同但不使用0字面值。

另一种方法是向您的项目添加apache collections并使用

执行此操作
CollectionUtils.isEmpty(<your list here>);

null这是true安全的,如果您的广告系列是nullempty,则会返回{{1}}。

答案 1 :(得分:1)

&#39;数据&#39;变量可能为null,因为即使您在开始时初始化它,也会再次进一步设置它。检查数据是否为空

if(data != null && data.size() != 0)