Java – I get a dead code warning when I try to write an if condition
•
Java
I received a dead code warning:
Topic topic = findTopicByID(point.getIDTopic()); if (topic != null) { ... } else if (topic == null) { // I get Dead code warning for every thing I write here! }
Sometimes when I get a warning but everything seems OK, I restart the IDE and I don't get a warning anymore! But this time
Edit:
public Topic findTopicByID(int IDTopic) { for (Topic topic : topics) if (topic.getID() == IDTopic) return topic; return null; }
Edit: full code:
Topic topic = Res.getSchedule().getTopic@R_78_2419@().findTopicByID(point.getIDTopic()); Section section = topic.findSectionByID(point.getIDSection()); if (topic != null) { View rowView = inflater.inflate(R.layout.daily_day_day_row,lLDoneWorks,false); TextView tVLabel = (TextView) rowView.findViewById(R.id.daily_day_day_row_label); TextView tVNum = (TextView) rowView.findViewById(R.id.daily_day_day_row_num); TextView tVTopic = (TextView) rowView.findViewById(R.id.daily_day_day_row_topic); TextView tVSection = (TextView) rowView.findViewById(R.id.daily_day_day_row_section); int color = topic.getColor(); tVLabel.setBackgroundColor(color); tVNum.setTextColor(color); tVTopic.setTextColor(color); tVSection.setTextColor(color); tVLabel.setText(topic.getName().substring(0,1).toUpperCase(Locale.US)); tVNum.setText(Integer.toString(point.getCount())); tVTopic.setText(topic.getName()); if (point.getIDSection() != Point.DEFAULT_SECTION) tVSection.setText(section.getName()); lLDoneWorks.addView(rowView); } else if (topic == null) { TopicArchived archivedTopic = Res.getSchedule().getTopic@R_78_2419@() .findArchivedTopicByID(point.getIDTopic()); if (archivedTopic == null) removedTopicsPoint += point.getCount(); else archivedTopicsPoint += point.getCount(); }
resolvent
Solution
This is because this line:
Section section = topic.findSectionByID(point.getIDSection());
If topic is null, it indicates that there is a NullPointerException and the rest of the code is not reached Therefore, every subsequent check for topic nulls is irrelevant: the compiler knows that the topic is not empty after the line
You should put this line in the first branch of the if statement
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码