Java avoiding null pointer exception in generic class -
okay here 2 classes.my aim insert in obt using generic class.in case trying strings.when call insert method in main keep getting:
exception in thread "main" java.lang.nullpointerexception @ obtcomparable.insert(obtcomparable.java:37) @ findtest.main(findtest.java:12)
i found problem: since var "data" null , can't use compare.
the question: how can change "data" avoid null pointer exception(it string).
generic obtcomparable class:
public class obtcomparable<type extends comparable<type>> { private boolean empty; private type data; private obtcomparable left; private obtcomparable right; public obtcomparable() { setempty(); } private void setempty() { empty = true; data = null; /////////////////// problem // left = null; right = null; } private void setdata(type reqdata) { if (empty) { empty = false; left = new obtcomparable(); right = new obtcomparable(); } data = reqdata; } public void insert(type insertdata) { int compare = data.compareto(insertdata); /////////////// here if (empty) setdata(insertdata); else if (compare < 0) left.insert(insertdata); else right.insert(insertdata); } public boolean find(type finddata) { int compare = finddata.compareto(data); if (empty) return false; else if (compare == 0) return true; else if (compare < 0) return left.find(finddata); else return right.find(finddata); } public int compareto(obtcomparable<type> other) { return 0; } } // class
test class:
public class test { public static void main(string[] args) { obtcomparable<string> obt = new obtcomparable<string>(); string [] insertstrings = new string [] { "my", "name", "is", "mark", "smith", "and", "my", "hobbies", "include", "films", "music", "computing" }; (int = 0; < insertstrings.length; i++) { obt.insert(insertstrings[i]); //////////// here system.out.println("inserting" + insertstrings[i]); } } // main } // class
in method you're referencing data
before call setdata
you're going problem.
a rewrite of insert around be
public void insert(type insertdata) { if (empty) { setdata(insertdata); } else { int compare = data.compareto(insertdata); if (compare < 0) left.insert(insertdata); else right.insert(insertdata); } }
you need apply similar changes find()
you should @ optional
way represent values may null. ideally, state of object set in constructor have valid object immediately.
Comments
Post a Comment