0

I have two string arrays in ar1 and ar2, and I am reading the input from file and storing in arrays , ar1 contains

Cat
Lam
Orange
Kam
Ramveer
None
Tue
Apple

ar2 contains

Dog
elephant
Kam
Monday
Parrot
Queen
Ramveer
Tuesday
Xmas

I am trying to sort the arrays in alphabetical order, and i am using Array.sort() , but getting the exception

Exception in thread "main" java.lang.NullPointerException
at java.util.ComparableTimSort.binarySort(ComparableTimSort.java:232)
at java.util.ComparableTimSort.sort(ComparableTimSort.java:176)
at java.util.ComparableTimSort.sort(ComparableTimSort.java:146)
at java.util.Arrays.sort(Arrays.java:472)
at CompareArrays.pr1(CompareArrays.java:51)
at CompareArrays.main(CompareArrays.java:86)

Java Result: 1 BUILD SUCCESSFUL (total time: 0 seconds)

Code

File file1= new File("C:\\Users\\Ramveer\\Desktop\\updates\\f1.txt");
File file2=new File("C:\\Users\\Ramveer\\Desktop\\updates\\f2.txt");
Scanner sc1=new Scanner(file1);
Scanner sc2=new Scanner(file2);
while(sc1.hasNextLine()){
ar1[c1]=sc1.nextLine();
c1++;
}

while(sc2.hasNextLine()){
ar2[c2]=sc2.nextLine();
c2++;
 }
  Arrays.sort(ar1);
  for(int k=0;k<c1;k++){
      System.out.println(ar1[k]);}

  }

Any help would be great. Thanks!

6
  • 2
    Your array probably contains a null item. Typically, if you declare an array of size 10 (for example) but only put 9 strings in it, the 10th item will be null. Commented Jun 26, 2013 at 11:36
  • 1
    Why is c1 not initialized?.. Commented Jun 26, 2013 at 11:37
  • Did you try debugging? That should sort the problem out quickly. Commented Jun 26, 2013 at 11:37
  • He might have left that part out though. Commented Jun 26, 2013 at 11:37
  • why don't you just print content of arrays and check where the problem is? First debug yourself. Commented Jun 26, 2013 at 11:37

5 Answers 5

8

Since you are using arrays, you must predict the number of entries in advance. It seems like your prediction is off, so some array elements stay null.

Please consider using ArrayList instead of a raw array. Sorting is done with Collections.sort.

Sign up to request clarification or add additional context in comments.

1 Comment

Indeed! I think you should use ArrayList over Array when you can.
1

Use an Arraylist as then you dont have to estimate the size of your array as the ArrayList grows dynamically as you add more strings, your code would go something like this

File file1= new File("C:\\Users\\Ramveer\\Desktop\\updates\\f1.txt");
File file2=new File("C:\\Users\\Ramveer\\Desktop\\updates\\f2.txt");
Scanner sc1=new Scanner(file1);
Scanner sc2=new Scanner(file2);
List<String> list1 = new ArrayList<String>()
List<String> list2 = new ArrayList<String>()

while(sc1.hasNextLine())
   list1.add(sc1.nextLine().toLowerCase());  //edited -- bad approach but would work if case not important


while(sc2.hasNextLine()){
   list2.add(sc2.nextLine().toLowerCase());  //edited -- bad approach but would work if case not important

Collections.sort(list1);
Collections.sort(list2);
for(String s: list1)
   System.out.println(s);

Or you could do this to implement a case insensitive sort, which would be better then altering the string as you add it to array

Collections.sort(list1, new Comparator<Object>() 
{
     @Override
     public int compare(Object o1, Object o2) 
     {
         String s1 = (String) o1;
         String s2 = (String) o2;
         return s1.compareToIgnoreCase(s2);
    }
}

Then repeat for list2. But an even better way would be to write a new comparator method as such

public class SortIgnoreCase implements Comparator<Object> {
    public int compare(Object o1, Object o2) {
        String s1 = (String) o1;
        String s2 = (String) o2;
        return s1.compareToIgnoreCase(s2);
    }
}

then call Collections.sort(list1, new SortIgnoreCase()); which is a cleaner way to write the code to sort multiple lists

6 Comments

Thanks @java Devil , approach work file but it gives the result Dog Kam Monday Parrot Queen Ramveer Tuesday Xmas elephant but in correct result elephant should be after Dog , why is this happening.
also when we use string.compareto method it will shows that kam is greater than elephant.
so i think it is not sorting while ignoring the case(not case sensitive), how can i do it without caring about capital and small letters(not case sensitive)
Thats correct that it is sorting case sensitive as the character value of lower case letters is higher than uppercase letters. If you want to ignore case when comparing strings you can use the toUpperCase() or toLowerCase() methods which are part of the String. But this will convert the whole string to that case so if you do s.toUpperCase.equals("UPPER") for s="upper" this will return true. I've edited above to add lowercase into list so sort will be correct.
There is also the methods equalsIgnoreCase() and compareToIgnoreCase() for Strings also
|
1

If your arrays are too big for the data, you'll have the default value of null in the unused elements; these null values will cause your exception.

Before loading and sorting your arrays, put blanks in all elements:

Arrays.fill(a1, "");
Arrays.fill(a2, "");

Comments

0

If you really want to use arrays then use this for reading:

    List<String> list1 = new ArrayList();
    while (sc1.hasNextLine()) {
        list1.add(sc1.nextLine());
    }
    String[] ar1 = list1.toArray(new String[list1.size()]);

If you can use List collection instead then:

    List<String> list1 = new ArrayList();
    while (sc1.hasNextLine()) {
        list1.add(sc1.nextLine());
    }
    Collections.sort(list1);

Comments

0

If your Array don't have null values Arrays.sort()works properly.

So it is better to use List to avoid that kind of a scenario.

Then you can convert your arrays to ArrayList and use Collections.sort() to sort them.

    String[] str1 = {"Cat","Lam","Orange","Kam","Ramveer","None","Tue","Apple"};
    String[] str2 = {"Dog","Elephant","Kam","Monday","Parrot","Queen","Ramveer","Tuesday","Xmas"};
    List<String> lst1=Arrays.asList(str1);
    List<String> lst2=Arrays.asList(str2);
    Collections.sort(lst1);
    Collections.sort(lst2);
    System.out.println(lst1+"\n"+lst2);

1 Comment

Using List<String> list1 = Arrays.asList(str1); would look neater.

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.