我如何摆脱NullPointerException?

时间:2014-10-20 23:21:41

标签: java exception exception-handling nullpointerexception

似乎无法摆脱NullPointerException错误。已编码约一年了。无论如何,我已经尝试了!xyz.equals(null)xyz[0] != null的所有可能组合,但似乎无法找到解决方案。我现在花了大约2个小时。将非常感谢帮助。感谢。

public class PedMapReducer extends Reducer<Text, Text, NullWritable, Text> 
{

Map<String, String> map = new LinkedHashMap<String, String>();
Map<String, String> ped = new LinkedHashMap<String, String>();
Set<String> s = new LinkedHashSet<String>();
List<String> arr = new ArrayList<String>();
String joined = null;

public void reduce(Text key, Iterable<Text> values, Context context)
{

    String [] lines = values.toString().split(",");

    if (lines[0] != null && lines[0] == "map_")
    {
        map.put(lines[1], lines.toString());
    }

    else if (lines[0] != null && lines[0] == "ped_")
    {
        ped.put(lines[1], lines.toString());
    }

}

public void cleanup(Context context) throws IOException, InterruptedException
{
    if(!map.entrySet().equals(null) && !ped.entrySet().equals(null))
    {
        for (Entry<String, String> entMap: map.entrySet())
        {
            for(Entry<String, String> entPed: ped.entrySet())
            {
                if(entMap.getKey().equals(entPed.getKey()))
                    joined = entMap.getValue() + "," + entPed.getValue();
            }
        }
        context.write(NullWritable.get(), new Text(joined));
    }


}

}

STACK

14/10/20 16:15:03 INFO mapreduce.Job: Task Id : attempt_1413663101908_0026_r_000110_0, Status : FAILED
Error: java.lang.NullPointerException
        at org.apache.hadoop.io.Text.encode(Text.java:450)
        at org.apache.hadoop.io.Text.set(Text.java:198)
        at org.apache.hadoop.io.Text.<init>(Text.java:88)
        at Map_Ped1.PedMapReducer.cleanup(PedMapReducer.java:49)
        at org.apache.hadoop.mapreduce.Reducer.run(Reducer.java:179)
        at org.apache.hadoop.mapred.ReduceTask.runNewReducer(ReduceTask.java:627)
    at org.apache.hadoop.mapred.ReduceTask.run(ReduceTask.java:389)
    at org.apache.hadoop.mapred.YarnChild$2.run(YarnChild.java:168)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:415)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1614)
    at org.apache.hadoop.mapred.YarnChild.main(YarnChild.java:163)

1 个答案:

答案 0 :(得分:2)

检查字符串相等时,代码使用==而不是.equals,因此不会将任何条目添加到任何集合中。改为使用.equals():

if (lines[0] != null && lines[0].equals("map_") )
{
    map.put(lines[1], lines.toString());
}

else if (lines[0] != null && lines[0].equals("ped_") )
{
    ped.put(lines[1], lines.toString());
}

由于这些集合(map和ped)为空,因此join将为null。 new Text(已加入)正在传递null,这可能是空指针异常的来源。文字&lt;。&初始化GT;暗示新的Text()是空指针异常的来源:

 at org.apache.hadoop.io.Text.<init>(Text.java:88)