Link to home
Start Free TrialLog in
Avatar of Jay Roy
Jay RoyFlag for United States of America

asked on

sorting Set - program hangs

Dear experts

I am trying to sort a set. My code below
public class Car implements Comparator<Car>{  
	
	private String model;
	private int year;
	
	public int compare(Car c1, Car c2){
		//return c2.getModel().compareTo(c1.getModel()); //sort by model
		return c2.getYear() - c1.getYear();  //sort by Year
	}

	public String getModel() {
		return model;
	}

	public void setModel(String model) {
		this.model = model;
	}

	public int getYear() {
		return year;
	}

	public void setYear(int year) {
		this.year = year;
	}

public static class MyCarTest{
Car c1 = new Car();		
Car c2 = new Car();
Set<Car> carSet = new HashSet<>();
		
private void addSet(){
			c1.setModel("Mercedes");
			c1.setYear(2012);
			
			c2.setModel("BMW");  //BMW
			c2.setYear(2013);    // 2014
			
			carSet.add(c1);
			carSet.add(c2);
			
			List<Car> carList = new ArrayList<Car>(carSet);
			//Collections.sort(carList);
			for(Car cars : carSet){
			System.out.println("Cars in set are>>" +cars.getModel() + "-"+ cars.getYear() );
			}
		}
public static void main(String[] args){
		MyCarTest test = new MyCarTest();
		test.addSet();
	}

Open in new window


When i uncomment this line >>Collections.sort(carList);
and try to save my java file, eclipse just freezes, happened 4 times already.
any idea what could be wrong?
thanks.
Avatar of krakatoa
krakatoa
Flag of United Kingdom of Great Britain and Northern Ireland image

Cast it to ArrayList ?

can't get your code to compile - errors are

C:\EE_Q_CODE>javac Car.java
Car.java:1: error: cannot find symbol
public class Car implements Comparator<Car>{
                            ^
  symbol: class Comparator
Car.java:30: error: cannot find symbol
Set<Car> carSet = new HashSet<>();
^
  symbol:   class Set
  location: class MyCarTest
Car.java:30: error: cannot find symbol
Set<Car> carSet = new HashSet<>();
                      ^
  symbol:   class HashSet
  location: class MyCarTest
Car.java:42: error: cannot find symbol
                        List<Car> carList = new ArrayList<Car>(carSet);
                        ^
  symbol:   class List
  location: class MyCarTest
Car.java:42: error: cannot find symbol
                        List<Car> carList = new ArrayList<Car>(carSet);
                                                ^
  symbol:   class ArrayList
  location: class MyCarTest
5 errors
ASKER CERTIFIED SOLUTION
Avatar of gurpsbassi
gurpsbassi
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial