1

Hello I have implemented this basic program which should sort out the strings that are inserted however it somehow is failing to insert the strings . For example if I implement :

TestSort t = new TestSort();
t.i("abc");
t.i("aab");

Can anybody see the error and help me fix this error please ?

Thank you


Here is the code :

public class TestSort {
    private int length;
    String[] data;

    public TestSort() {
        length = 0;
    }

    public void i(String value) {
        data[length] = value;   
        setSorted(data);
        length++;
    }

    public void setSorted(String data[]) {
        for(int i = data.length-1; i >= 0; i--) {
            for(int j = 0; j < i; j++) {
                if(data[j].compareTo(data[j + 1]) > -1) {
                    String temp = data[j];
                    data[j] = data[j + 1];
                    data[j + 1] = temp;
                }
            }
        }

        for(int i = 0; i < data.length; i++) {
            System.out.print(data[i] +" ");
        }
    }
}
10
  • How is it failing? Is there an exception? Does it simply not insert? Commented Jan 28, 2015 at 12:06
  • Please fix your code indentation and use the proper java casing (classes start with uppercase, methods with lowercase) Commented Jan 28, 2015 at 12:06
  • 1
    I imagine you're getting an IndexOutOfBoundsException but can you please post the stack-trace of your error. Commented Jan 28, 2015 at 12:07
  • 2
    I don't think you have initialized the String[] data array, have you? Commented Jan 28, 2015 at 12:09
  • 2
    You should look into ArrayList as an alternative to standard arrays. With ArrayList you don't have to worry about making sure your array is large enough to hold the data to insert. Change String[] data to List<String> data. Add into your constructor this.data = new ArrayList<String>() and then look at how to use the List interface. Commented Jan 28, 2015 at 12:12

5 Answers 5

1

You don't initialize the array data. So it is set null, and accesses with data[i] will get you an NullPointerException. Even if you initialize this field, it will not work, as Arrays in Java have a fixed size, you have to reallocate the Array, if you insert a new value. You should try a List-implementation instead.

So the code should initialize in the constructor:

data = new ArrayList<String>();

and insertion would change to

data.add(value);
Sign up to request clarification or add additional context in comments.

3 Comments

Exception in thread "main" java.lang.NullPointerException at ads2.testsort.i(testsort.java:28) at ads2.Main.main(Main.java:345) Java Result: 1
Exception in thread "main" java.lang.NullPointerException at ads2.testsort.i(testsort.java:28) at ads2.Main.main(Main.java:345) Java Result: 1
Yes, as I wrote in my answer, that is predictable if you access a null-object. I added some codesnippets for using Lists to my answer, that should you help a bit.
0

you can change your constructor code as (String array max length can be taken as input parameter):

public testsort() 

{

   data = new String[10];
   length = 0;

}

But if you are not sure with the size of array you can use ArrayList.

You are getting exception because you are comparing with data[j+1] that is still null. first time when you call

t.i("abc");

there is only one reference in data array that is pointing to String literal "abc" and that is at index 0. index 1 is still referring to null. first String is already sorted so no need to sort that. if you are having more than one string then you should call setSorted() method.

to solve this you can put your condition in loop as:

if((data[j] != null && data[j+1] != null) &&(data[j].compareTo(data[j + 1]) > -1))

9 Comments

"Must be taken as input parameter"
Hello Prashant , I just did now I am getting Exception in thread "main" java.lang.NullPointerException at java.lang.String.compareTo(String.java:1139) at ads2.testsort.SetSorted(testsort.java:44) at ads2.testsort.i(testsort.java:32) at ads2.Main.main(Main.java:345) Java Result: 1
The point here is that I am trying to do this without ArrayList
No, the exception is because he uses data.length (the length of the array) instead of length (his own length pointer). That should work, as j+1 is at max length -1 then.
Hi Prashant , thanks , but can you then please show me how to fix this if I am comparing with data[j+1]
|
0

A working example but still: use a List and life is much easier :-)

public class Test {
private int length;
private String[] data;

public Test(int arrayLength) {
    // INITIALIZE YOU ARRAY --> No NULLPOINTEREXCEPTION!
    data = new String[arrayLength];
    length = 0;
}

public void i(String value) {
    data[length] = value;
    length++;
}

public void setSorted() {
    for (int j = 0; j < data.length - 1; j++) {
           if (data[j].compareTo(data[j + 1]) > -1) {
                String temp = data[j];
                data[j] = data[j + 1];
                data[j + 1] = temp;
            }

    }
    for (String s : data) {
        System.out.println(s);
    }
}

public static void main(String[] args) {
    Test t = new Test(5);
    t.i("bbb");
    t.i("aaa");
    t.i("ccc");
    t.i("zzz");
    t.i("ddd");
    // USE SETSORTED HERE --> else you fill your array with the same elements
    t.setSorted();
}

}

3 Comments

Hi Black_Buster , I tried your code with t.i("bbb"); t.i("aaa"); t.i("ccc"); t.i("zzz"); t.i("ddd"); // USE SETSORTED HERE --> else you fill your array with the same elements t.setSorted(); , but I am just getting the same elements as output
output: aaa bbb ccc ddd zzz
This would work but its a poor approach. You have to fill every position of your array else you would get NPE, you ArrayList instead.
0

The variable 'data' is null since it is nowhere initialized hence giving null pointer exception. Since 'data' is an array and as per the rule whenever an array is defined, it has to be of defined length. for e.g if we consider your case. 'data' can be initialized as :-

 String[] data = new String[any numerical value]

the numerical value will be its length i.e. the maximum number of elements it can hold.

Secondly, as per your program statement :-

data[length] = value;

is trying to assign value at data's [length] index which is completely wrong since you haven't defined the length therefore how could you guess the index's value. Therefore your this approaoch is logically wrong. For such situation i.e. whenever we're unaware about the length of the array, use of ArrayList is suggested. Therefore your program can be re-written by two ways:-

1) Either define the length of the array

String[] data = new String[n];

where n ranges from at least 1 to any positive integer.

2) By using ArrayList

public class Main {
    List<String> data;

    public Main(){
        data = new ArrayList<String>();
    }

    public static void main(String... q){

        Main m = new Main();
        m.insertData("abc");
        m.insertData("zxy");
        m.insertData("aab");
        m.insertData("aaa");
        m.showData();

    }

    public void insertData(String str){
        data.add(str);
        Collections.sort(data);
    }

    public void showData(){
        if(data!=null && !data.isEmpty()){
            for(String s : data){
                System.out.println(s);
            }
        }
    }


}

output:-

aaa

aab

abc

zxy

Hope this helps.

Comments

0

as Mnementh suggested, the reason for NPE is that you have created the field data of type String[] but you never initialized it.

Other answers have provided every reason on why your code throwing ugly errors; I have just improved your code by replacing your String[] with List<String> so you don't have to worry about the size of your array anymore. Sorting is also simplified now using Collections.sort().

have a look,

class test1 {
    public static void main(String[] args) {
        Test sorting = new Test();
        sorting.input("abc");
        sorting.input("cba");
        sorting.input("aab");
        sorting.setSorted();
    }
}

class Test {
    private List<String> data = new ArrayList<String>();
    public void input(String value) {data.add(value);}
    public void setSorted() {
        Collections.sort(data);
        for (String current : data) {
            System.out.println(current);
        }
    }
}

if you are using Java 8, then you can use Arrays.parallerSort(), it performs sorting the same way as Collection.sort but with a parallel implementation.

Current sorting implementations provided by the Java Collections Framework > (Collections.sort and Arrays.sort) all perform the sorting operation sequentially in the calling thread. This enhancement will offer the same set of sorting operations currently provided by the Arrays class, but with a parallel implementation that utilizes the Fork/Join framework. These new API's are still synchronous with regard to the calling thread as it will not proceed past the sorting operation until the parallel sort is complete.

to implement it, replace Collections.sort with Arrays.parallelSort in the above code,

Replace,

Collections.sort(data);

with,

Arrays.parallelSort(data.toArray(new String[data.size()]));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.