1

Why is the following piece of code not working?

import java.util.Comparator;


public class TestInner {


public static void main(String[] args) {

    Comparator<String> comp = new Comparator<String>(){

        private String sample = null;
        @Override
        public int compare(String arg0, String arg1) {
            // TODO Auto-generated method stub
            return arg0.compareTo(arg1);
        }

        public void setText(String t1){
            sample = t1;
        }

    };
    // compiler error - Method is undefined for the type Comparator<String> 
    comp.setText("xyz"); 

}

}

I have used Comparator just in the sample code. The same is happening with Comparator of any object.

I'm creating an inner class that has implemented the Comparator interface, why is it now allowing me to add new methods here?

4

4 回答 4

4

不允许这样做的原因是因为您Comparator的左侧有 a=而 aComparator没有setText方法。要解决此问题,您必须使用setText方法命名一个类并在左侧使用该命名类。例如,此代码将编译:

package com.sandbox;

import java.util.Comparator;

public class Sandbox {

    public static void main(String[] args) {

        MyComparator comp = new MyComparator();
        // compiler error - Method is undefined for the type Comparator<String> 
        comp.setText("xyz");

    }

    private static class MyComparator implements Comparator<String> {

        private String sample = null;

        @Override
        public int compare(String arg0, String arg1) {
            // TODO Auto-generated method stub
            return arg0.compareTo(arg1);
        }

        public void setText(String t1) {
            sample = t1;
        }    
    }        
}

请注意,此代码仍然无法编译,因为您没有放在MyComparator左侧:

package com.sandbox;

import java.util.Comparator;

public class Sandbox {

    public static void main(String[] args) {

        Comparator comp = new MyComparator();
        // compiler error - Method is undefined for the type Comparator<String>
        comp.setText("xyz");

    }

    private static class MyComparator implements Comparator<String> {

        private String sample = null;

        @Override
        public int compare(String arg0, String arg1) {
            // TODO Auto-generated method stub
            return arg0.compareTo(arg1);
        }

        public void setText(String t1) {
            sample = t1;
        }

    }


}
于 2013-06-06T04:56:30.657 回答
0

因为 Comparator 没有声明 setText() 方法,并且您尝试使用 Comparator 引用变量调用该方法。

于 2013-06-06T05:18:50.130 回答
0

创建内部类时,它没有可以直接使用的类型。

您将内部类分配给类型的变量,Comparator因此当您引用该变量时,您只能访问由 type 定义的方法Comparator

如果你想在外部使用其他方法,你应该创建一个单独的类implements Comparator

于 2013-06-06T04:58:44.883 回答
0

Comparator接口没有setText()方法。您已将变量的类型声明为Comparator,而不是某个客户类,因此您可以调用的唯一方法是属于Comparator

于 2013-06-06T05:04:56.440 回答