//这是一个研究集合如何工作的小代码,但是当我在 main 方法中创建一个 Mountain 对象时,它会出错。最后进一步解释。
import java. util. * ;
public class sortMountains {
class Mountain {
String name;
int height;
Mountain(String n, int h) {
name = n;
height = h;
}
public String toString( ) {
return name + + height;
}
}
List<Mountain> mtn = new ArrayList<Mountain> ();
class NameCompare implements Comparator <Mountain> {
public int compare(Mountain one, Mountain two) {
return one.name. compareTo(two. name);
}
}
class HeightCompare implements Comparator <Mountain> {
public int compare(Mountain one, Mountain two) {
return (two. height - one. height) ;
}
}
public void go() {
mtn.add(new Mountain("Longs ", 14255));
mtn.add(new Mountain("Elbert ", 14433));
mtn.add(new Mountain("Maroon " , 14156));
mtn.add(new Mountain("Castle ", 14265));
System.out.println("as entered:\n" + mtn);
NameCompare nc = new NameCompare();
Collections.sort(mtn, nc);
System.out.println("by name:\n'" + mtn);
HeightCompare hc = new HeightCompare();
Collections.sort(mtn, hc);
System.out.println("by height:\n " + mtn);
}
public static void main(String args[]){
sortMountains sorting=new sortMountains();
sorting.go();
//error line Mountain a=new Mountain("Everest",12121);
}
}
上面编译时没有错误行工作正常,但是当我想在 main 方法中创建一个 Mountain 对象时,它给出了一个错误“非静态不能从静态方法引用”