Methods are not first class objects in Java. Only objects and primitive data types can be passed to methods.

Instead you should declare an interface which declares the function you want to pass; for example


public interface Comparable {

  public abstract int compare(Object o1, Object o2);


Then declare that your method takes an object of this type. For example,


  public void sort(Object[] o, Comparable c) {
    boolean done = false;
    while (!done) {
      done = true;
      for (int i = 0; i < o.length - 1; i++) {
      if ([i], o[i+1]) < 0) {
        swap(o[i], o[i+1]);
        done = false;

Each class you want to compare then needs its own class which implements Comparable. For example,


public class StringCompare implements Comparable {

  public int compare(Object o1, Object o2) {
    String s1 = (String) o1;
    String s2 = (String) o2;
    return s1.compareTo(s2);

It helps that Object is a superclass for all object types.

Posted in: Java

Related FAQ's

Marius Ion ANGEL HOT SOFT LLC (800) 316-7677