Exception:java.lang.NullPointerException when comparing two strings of two different string arrays -


i'm coding trough codingbat.com/java , ran error don't understand. got 2 string arrays , want compare them. if use arrays works fine (but result not right). right result programmed helper function eliminates duplicates of array. tested helper function, returns array shortened of duplicates.

i can retrieve values in new arrays _a[i] etc., , don't errors, if use _a[0].equals(_b[0]) or _a[0].compareto(_b[0]) nullpointerexception (_a[0] == _b[0] works fine...).

if use original arrays a,b code runs without problems. don't comprehend why nullpointerexception there.

thanks help!

code:

public int commontwo(string[] a, string[] b) {        string[] _a = killduplicate(a);       string[] _b = killduplicate(b);        int ai=0, bi=0,count=0;        (int = 0; ai < _a.length & bi < _b.length; i++){          if ( _a[ai].compareto(_b[bi]) > 0) { //nullpointerexception here, not if use a,b             bi++;          } else if ( _a[ai].compareto(_b[bi]) < 0){  //nullpointerexception here, not if use a,b             ai++;          } else {              count++;             ai++;             bi++;          }         }       return count; } 

helper function:

 public string[] killduplicate(string[] a){       string temp = "";      int counter = 0, counter2 = 0;       (int = 0; < a.length; i++){         if (! a[i].equals(temp)){            temp = a[i];         } else {            a[i] = "";            counter++;         }      }       string[] result = new string[a.length - counter];       (int = 0; counter2 < counter; i++){         if (a[i].equals("")) {            counter2++;         }      } else {         result[i-counter2] = a[i];      }      return result;  } 

i guess assume array of strings sorted, otherwise killduplicate method wouldn't make sense @ all.

the problem code in second for loop in killduplicate method iterate condition counter2 < counter says iterate until found duplicates passed. when find last duplicate exit without filling rest of array. try example: new string[]{"a", "a", "b", "c"} you'll [a, null, null].

there numerous things can improved simplest modification of code below. (i've changed second for loop) public string[] killduplicate(string[] a) {

    string temp = "";     int counter = 0, counter2 = 0;      (int = 0; < a.length; i++) {         if (!a[i].equals(temp))             temp = a[i];         else {             a[i] = "";             counter++;         }     }      string[] result = new string[a.length - counter];      (int = 0; < a.length; i++) {         if (a[i].equals("")) continue;         result[counter2] = a[i];         counter2++;     }      return result; } 

Comments

Popular posts from this blog

image - ClassNotFoundException when add a prebuilt apk into system.img in android -

I need to import mysql 5.1 to 5.5? -

Java, Hibernate, MySQL - store UTC date-time -