0

I wrote a code for keeping record of indices even after sorting but it is showing me null pointer exception.I read other threads on same topic but still couldn't find.

import java.io.*;
import java.util.*;

public class Solution {
class Order{
    public int index;
    public int sum;

    public void setIndex(int index){
        this.index = index;
    }
    public void setSum(int sum){
        this.sum = sum;
    }
    public int getSum(){
        return this.sum;
    }
    public int getIndex(){
        return this.index;
    }
}
public static void main(String[] args) {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
    Scanner sc  = new Scanner(System.in);
    int N = sc.nextInt();
    Order array[] = new Order[N];
    int index = 0;
    int sum = 0;
    while(index<N){
        int input1 = sc.nextInt();
        int input2 = sc.nextInt();
        //line 32
        array[index].setIndex(index);
        array[index].setSum(input1+input2);
        index++;
    }
    ArrayList<Order> list = new ArrayList<Order>(Arrays.asList(array));

    Collections.sort(list, new Comparator<Order>(){
        @Override
        public int compare(Order o1, Order o2){
            return(Integer.compare(o1.getSum(), o2.getSum()));
        }
    });

    System.out.println(list);

}
}

error is like this :

Exception in thread "main" java.lang.NullPointerException
at Solution.main(Solution.java:32)

I am passing i, still null pointer why?

minigeek
  • 2,766
  • 1
  • 25
  • 35

1 Answers1

0

You initialized array with Order array[] = new Order[N];, but the array is full of null objects. You need to initialize every element with new Order and then use setters

James Cube
  • 421
  • 3
  • 12