Dhruv
Dhruv

Reputation: 21

Why am I getting a NoSuchMethodError in this code?

import java.util.*;

public class Lab50 {    
    public static void main(String[] args) {
        System.out.println("Student Information");
        TreeSet set = new TreeSet();
        set.add(new Student(87, "Andy"));
        set.add(new Student(99, "Bichel"));
        set.add(new Student(12, "Chuck"));
        set.add(new Student(45, "David"));

        Iterator it = set.iterator();
        while (it.hasNext()) {
            System.out.println(it.next());
        }
    }
}

class Student implements Comparable {    
    int sid;
    String name;

    Student(int sid, String name) {
        this.sid = sid;
        this.name = name;
    }

    public int compareTo(Object obj) {
        if (obj instanceof Student) {
            Student st = (Student) obj;
            return this.sid - st.sid;
        }
        return 0;
    }

    public String toString() {
        return sid + "\t" + name;
    }
}

I am getting the error on the first line of adding the element of Andy. Following is the error message on the console :

Exception in thread "main" java.lang.NoSuchMethodError: Student.(ILjava/lang/String;)V at Lab50.main(Lab50.java:6)

Upvotes: 0

Views: 1262

Answers (1)

GhostCat
GhostCat

Reputation: 140427

The javadoc for that exception is pretty clear:

Thrown when a particular method cannot be found.

This means: at runtime, when your JVM executes a class; the JVM wants to invoke a certain method. It looks into the corresponding class - and it doesn't find a method with that name/signature in that class. In your case, the compiled Student.class simply does not contain a constructor that fits the intended usage.

That happens when you have A.java and B.java; and A is calling something in B. Then you change B.java, and re-compile it; but you forgot to recompile A.java.

In other words: you ran into a inconsistency where some A class is trying to use a method of some B class that B.class actually does not contain.

The real answer here: make sure that your compiled output is always consistent. Meaning: recompile everything together.

In the "real" world, such things are handled by build systems for example. In other words: if you want to avoid such issues, either use an IDE that keeps track of all your classes in your project and tells you about such problems when you insert them into your code; or learn how to use a build system such as ant, maven, gradle, ... that allows to "clean" up your build output, or that automatically re-compiles all artifacts that need re-compiling.

Upvotes: 1

Related Questions