-1
public class CollectionsDemo4 {

 public static void main(String a[]){
     
    List<Empy> emps = new ArrayList<Empy>();
    
    Empy empobj1=new Empy(10, "Raghu", 25000);
    Empy empobj2=new Empy(120, "Krish", 45000);
    Empy empobj3=new Empy(140, "John", 14000);
    Empy empobj4=new Empy(14000, "Kishore", 24000);
    
    emps.add(empobj1);
    emps.add(empobj2 );
    emps.add(empobj3 );
    emps.add(empobj4 );
    Empy minSal = Collections.min(emps, new EmpyComp());
    System.out.println("Employee with min salary: "+minSal);

    for (Object value : emps) {
     System.out.println("Value = " + value);
     } 
    System.out.println("The initial list is :"+emps.toString());

      Comparator<Empy> cmp = Collections.reverseOrder(new EmpyComp() );
 
      System.out.println("");
      Collections.sort(emps, cmp);  
      System.out.println("The sorted reverse list is :"+emps.toString());
  
    Integer  number = null;
    int b = number.intValue();
        int index = Collections.binarySearch(emps, new Empy(b, null,14000), cmp); 
        System.out.println("Found at index  " + index); 
 }
 }

 class EmpyComp implements Comparator<Empy>{

   @Override
     public int compare(Empy e1, Empy e2) {
    return e1.getSalary().compareTo(e2.getSalary());
  }
 }

class Empy{
    ......
    public String toString(){//
        return id+"  "+name+"   "+salary;
    }
} 

int index = Collections.binarySearch(emps, new Empy(b, null,14000), cmp);
Throw the Exception in thread "main" java.lang.NullPointerException. This is the full trace.

How do we let the code just search 3rd column which is salary?

andy tang
  • 31
  • 3
  • You'll need to show the code for `Empy` and `cmp`, and the full stack trace of the error, otherwise (or probably "even with") this is going to be closed as a dup. – Ken Y-N Sep 09 '20 at 23:56
  • `null` is converted to `int` where? There is no such code in your question, and there can't be. – user207421 Sep 10 '20 at 04:44
  • This question is totally different from “What is a NullPointerException, and how do I fix it”. Think about it before associating to it. – andy tang Sep 10 '20 at 18:37
  • OK, if null cannot converted to int. How to search for just 3rd column. – andy tang Sep 10 '20 at 18:39
  • To Marquis of Lorne : please search for "Conversion from null to int possible?" in stack overflow. Integer number = null; int b = number.intValue(); – andy tang Sep 10 '20 at 18:41

1 Answers1

0

Solution

Maybe map out the values before you search?

List<Integer> salaries = emps.map(Empy::getSalary); // Or whatever getter you use
int index = salaries.indexOf(14000);
System.out.println("Found at index  " + index); 

Explanation

    Integer  number = null;
    int b = number.intValue();

You can't call method on a null object. That's why you are getting a NullPointerException

LeoYulinLi
  • 129
  • 6