//This is a small code to study how collection works but when I create an Mountain object in main method it gives an error. Explained further in the end.
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);
}
}
The above when compiled without error line works fine but when I want to create an object of Mountain in main method it gives an error "non-static cannot be referenced from static method"