Results 1 to 20 of 20
Like Tree1Likes
  • 1 Post By superhaNds

Thread: Comparable and Iterable Interface

  1. #1
    ahanslot is offline Member
    Join Date
    Sep 2013
    Posts
    26
    Rep Power
    0

    Default Comparable and Iterable Interface

    Hi,

    I have a task to create a Java OOP program, I have a class Team which requires a comparable and iterable interface, the only way I know how to do this is either:

    public class Team implements Iterable <Mechanic>

    or

    public class Team implements Comparable <Mechanic>

    how do I add both?

    Comparable and Iterable Interface-screenshot-2014-01-01-12.50.34.png

  2. #2
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,783
    Blog Entries
    7
    Rep Power
    21

    Default Re: Comparable and Iterable Interface

    The syntax is easy:

    Java Code:
    public class Team implements Iterable <Mechanic>, Comparable <Mechanic> {
       // your implementation goes here ...
    }
    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  3. #3
    ahanslot is offline Member
    Join Date
    Sep 2013
    Posts
    26
    Rep Power
    0

    Default Re: Comparable and Iterable Interface

    Quote Originally Posted by JosAH View Post
    The syntax is easy:

    Java Code:
    public class Team implements Iterable <Mechanic>, Comparable <Mechanic> {
       // your implementation goes here ...
    }
    kind regards,

    Jos
    thanks i will try it out :)

    how can I add the compareTo method to compare the calculated points of two teams, I have tried

    Java Code:
    	public int compareTo(Team other) { 
    		
    		int result = this.Name.compareTo(other.Name);
    		
    		if (result ==0){
    			result = this.points.compareTo(other.points);
    		}
    		return result;
    	}
    but I can't use compareTo with int, am I comparing the wrong fields?
    Last edited by ahanslot; 01-01-2014 at 05:18 PM.

  4. #4
    superhaNds is offline Senior Member
    Join Date
    Apr 2013
    Location
    Sweden
    Posts
    268
    Rep Power
    2

    Default Re: Comparable and Iterable Interface

    you can't use compareTo on a primitive, but you can use the wrapper class Integer, which implements the Comparable<Integer>.

    Or use the static method compare of the Integer class
    Last edited by superhaNds; 01-01-2014 at 06:51 PM.
    gimbal2 likes this.

  5. #5
    ahanslot is offline Member
    Join Date
    Sep 2013
    Posts
    26
    Rep Power
    0

    Default Re: Comparable and Iterable Interface

    Quote Originally Posted by superhaNds View Post
    you can't use compareTo on a primitive, but you can use the wrapper class Integer, which implements the Comparable<Integer>.

    Or use the static method compare of the Integer class
    thanks I have implemented all of the methods, how would I output in order the championship standings including team name, and points, as well as the full name of each driver within the team and their respective points, I have tried firstly calling the sortTeamsOnPoints method this works as when I print the values via toString the teams are in order of points.

    I have then tried using the iterator, using a for each loop to display the contents of the arraylist but only the team name, points and drivers and their points but no luck is this possible? If this is also possible with a for each as I am display the standings for the competition would i be able to have a number infront that is printed

    e.g. 1) Team ranked 1st Points Drivers Points
    2) Team ranked 2nd Points Drivers Points etc

    thanks

  6. #6
    superhaNds is offline Senior Member
    Join Date
    Apr 2013
    Location
    Sweden
    Posts
    268
    Rep Power
    2

    Default Re: Comparable and Iterable Interface

    If the list is sorted according to team points where are having trouble? Why doesn't the contents of the list satisfy your goal? What information do you need and what are you getting?
    If you want to print the standings, concatenate a number as the loop goes. print(i + ")" +...). Otherwise post some code example to understand you better.

  7. #7
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,367
    Rep Power
    6

    Default Re: Comparable and Iterable Interface

    Quote Originally Posted by superhaNds View Post
    Or use the static method compare of the Integer class
    Eh? I didn't even realize it was there! I've been using Integer.valueOf(someint).compareTo() until now to make use if the internal instance cache :/

    Note to self: it doesn't matter how often you've seen the actual javadoc in question: periodically check them anyway.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  8. #8
    superhaNds is offline Senior Member
    Join Date
    Apr 2013
    Location
    Sweden
    Posts
    268
    Rep Power
    2

    Default Re: Comparable and Iterable Interface

    That's why the doc is no.1 on my bookmarks, but I really do need it because of assignments and now exams :)

  9. #9
    ahanslot is offline Member
    Join Date
    Sep 2013
    Posts
    26
    Rep Power
    0

    Default Re: Comparable and Iterable Interface

    Quote Originally Posted by superhaNds View Post
    If the list is sorted according to team points where are having trouble? Why doesn't the contents of the list satisfy your goal? What information do you need and what are you getting?
    If you want to print the standings, concatenate a number as the loop goes. print(i + ")" +...). Otherwise post some code example to understand you better.
    this is my code in the Championship class

    Java Code:
    import java.util.ArrayList; //import as instance variable is of type ArrayList
    import java.util.Iterator;
    import java.util.Collections; //import to use sort method on ArrayList
    
    
    public class Championship implements Iterable <Team> {
    	
    	//Fields
    	private ArrayList<Team> teams;
    
    	//Constructor
    	public Championship() {
    		teams = new ArrayList<Team>();
    	}
    
    	//methods
    	//sort team on points
    	public void sortTeamsOnPoints(){
    			Collections.sort(teams, Collections.reverseOrder());
    		
    	}
    	
    	
    	//add team
    	public void add(Team t) {
            teams.add(t);
        }
    	
    	//remove team
    	public void remove(int i) {
            teams.remove(i);
        }
    
    	//get team
    	public Team get(int i) {
            Team t = null;
            if (0 <= i && i < teams.size()) {
                t = teams.get(i);
            } else {
                t = null; // i is out of range
            }
            return t;
        }
    	
    	//get team size
    	public int size() {
            return teams.size();
        }
    	
    	//clear
    	public void clear() {
            teams.clear();
        }
    	
    	//iterator
    	public Iterator<Team> iterator() {
    		return teams.iterator(); 
    	}
    
    	//to String
    	@Override
    	public String toString() {
    		return "Championship [teams=" + teams + "]";
    	}
    }
    I wanted to utlise the iterator to loop through the arraylist using a for each loop and print out the teams instead of coding println for every team name

  10. #10
    superhaNds is offline Senior Member
    Join Date
    Apr 2013
    Location
    Sweden
    Posts
    268
    Rep Power
    2

    Default Re: Comparable and Iterable Interface

    well, the syntax is simple.

    Java Code:
    for (Team t : teams) { // print the toString of 't' or concatenate them and return them all }
    you can also add a number in front or whatever you wish to make it look like you want.

  11. #11
    ahanslot is offline Member
    Join Date
    Sep 2013
    Posts
    26
    Rep Power
    0

    Default Re: Comparable and Iterable Interface

    Quote Originally Posted by superhaNds View Post
    well, the syntax is simple.

    Java Code:
    for (Team t : teams) { // print the toString of 't' or concatenate them and return them all }
    you can also add a number in front or whatever you wish to make it look like you want.
    thanks for the reply from my research thats what I am looking for a for each loop but when I put it in my testing class where I have simply created 3 teams, placed drivers and mechanics into the teams and added the teams to the championship I get an error teams cannot be resolved to a variable? so it can't find the teams Arraylist?

    my testing class

    Java Code:
    import java.util.ArrayList; //import as instance variable is of type ArrayList
    import java.util.Iterator;
    import java.util.Collections; //import to use sort method on ArrayList
    
    
    public class Championship implements Iterable <Team> {
    	
    	//Fields
    	private ArrayList<Team> teams;
    
    	//Constructor
    	public Championship() {
    		teams = new ArrayList<Team>();
    	}
    
    	//methods
    	//sort team on points
    	public void sortTeamsOnPoints(){
    			Collections.sort(teams, Collections.reverseOrder());
    		
    	}
    	
    	
    	//add team
    	public void add(Team t) {
            teams.add(t);
        }
    	
    	//remove team
    	public void remove(int i) {
            teams.remove(i);
        }
    
    	//get team
    	public Team get(int i) {
            Team t = null;
            if (0 <= i && i < teams.size()) {
                t = teams.get(i);
            } else {
                t = null; // i is out of range
            }
            return t;
        }
    	
    	//get team size
    	public int size() {
            return teams.size();
        }
    	
    	//clear
    	public void clear() {
            teams.clear();
        }
    	
    	//iterator
    	public Iterator<Team> iterator() {
    		return teams.iterator(); 
    	}
    
    	//to String
    	@Override
    	public String toString() {
    		return "Championship [teams=" + teams + "]";
    	}
    }

  12. #12
    superhaNds is offline Senior Member
    Join Date
    Apr 2013
    Location
    Sweden
    Posts
    268
    Rep Power
    2

    Default Re: Comparable and Iterable Interface

    you posted the championship class again.

  13. #13
    ahanslot is offline Member
    Join Date
    Sep 2013
    Posts
    26
    Rep Power
    0

    Default Re: Comparable and Iterable Interface

    Quote Originally Posted by superhaNds View Post
    you posted the championship class again.
    sorry my mistake please find my testing class below:

    Java Code:
    public class Tessting {
    
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		
    		//Team1
    		Team Team1 = new Team();
    		Team1.setName("Red Bull");
            Driver driver1 = new Driver(new Details("Sebastien Vettel", "65 Red Ave"), 220000, 20);
            Driver driver2 = new Driver(new Details("Mark Webber", "432 Bull Close"), 220000, 13);
            Mechanic mechanic1 = new Mechanic(new Details("Ahmed Hanslot,", "22 Racing Green"), 120000, "Basic Engineer", false);
            Mechanic mechanic2 = new Mechanic(new Details("Gregg Fish,", "345 Maythorpe Road"), 120000, "Data Strategist", false);
            Mechanic mechanic3 = new Mechanic(new Details("Wayne Cobb,", "6 Thunder Close"), 120000, "Driver Support", true);
            Mechanic mechanic4 = new Mechanic(new Details("Julie May,", "18 Yourview Avenue"), 120000, "Driver Support", true);
                  
            Team1.setDriver1(driver1);
            Team1.setDriver2(driver2);
            Team1.addMechanic(mechanic1);
            Team1.addMechanic(mechanic2);
            Team1.addMechanic(mechanic3);
            Team1.addMechanic(mechanic4);
            
            
          //Team2
          	Team Team2 = new Team();
          	Team2.setName("Mercedes AMG Petronas");
            Driver driver3 = new Driver(new Details("Lewis Hamilton", "18 Farnborough Way"), 460000, 6);
            Driver driver4 = new Driver(new Details("Nico Rosberg", "99 Lapson Pass"), 460000, 19);
            Mechanic mechanic5 = new Mechanic(new Details("Dhruv Patel,", "82 Grantham Close"), 125000, "Basic Engineer", false);
            Mechanic mechanic6 = new Mechanic(new Details("John O'Finn,", "912 Jupiter Road"), 125000, "Data Strategist", false);
            Mechanic mechanic7 = new Mechanic(new Details("Jack Mable,", "2 Winner Road"), 110000, "Driver Support", true);
            Mechanic mechanic8 = new Mechanic(new Details("Bob Barmann,", "19 Mel Avenue"), 110000, "Driver Support", true);
                        
            Team2.setDriver1(driver3);
            Team2.setDriver2(driver4);
            Team2.addMechanic(mechanic5);
            Team2.addMechanic(mechanic6);
            Team2.addMechanic(mechanic7);
            Team2.addMechanic(mechanic8);
            
            //Team1
          	Team Team3 = new Team();
          	Team3.setName("Lotus F1 Renault");
            Driver driver5 = new Driver(new Details("Kimi Raikkonen", "18 Farnborough Way"), 460000, 26);
            Driver driver6 = new Driver(new Details("Romain Grosjeam", "99 Lapson Pass"), 460000, 19);
            Mechanic mechanic9 = new Mechanic(new Details("Dhruv Patel,", "82 Grantham Close"), 125000, "Basic Engineer", false);
            Mechanic mechanic10 = new Mechanic(new Details("John O'Finn,", "912 Jupiter Road"), 125000, "Data Strategist", false);
            Mechanic mechanic11 = new Mechanic(new Details("Jack Mable,", "2 Winner Road"), 110000, "Driver Support", true);
            Mechanic mechanic12 = new Mechanic(new Details("Bob Barmann,", "19 Mel Avenue"), 110000, "Driver Support", true);
                        
            Team3.setDriver1(driver5);
            Team3.setDriver2(driver6);
            Team3.addMechanic(mechanic9);
            Team3.addMechanic(mechanic10);
            Team3.addMechanic(mechanic11);
            Team3.addMechanic(mechanic12);
                  
    
            Championship formula1 = new Championship();
            formula1.add(Team1);
            formula1.add(Team2);
            formula1.add(Team3);
    		System.out.println(formula1.toString());
    		
    
    		System.out.println(Team1.getName() + " " + Team1.getPoints());
    		System.out.println(Team2.getName() + " " + Team2.getPoints());
    		System.out.println(Team3.getName() + " " + Team3.getPoints());
    		
    		Team1.calculatePoints();
    		Team2.calculatePoints();
    		Team3.calculatePoints();
    		formula1.sortTeamsOnPoints();
    		
    		System.out.println(formula1.toString());
    		
    		//add for each to print team standings - team name + driver1 + driver 2 +  points
    			
    	}
    }

  14. #14
    superhaNds is offline Senior Member
    Join Date
    Apr 2013
    Location
    Sweden
    Posts
    268
    Rep Power
    2

    Default Re: Comparable and Iterable Interface

    ok, I assume that you tried using 'teams' in the loop and as expected the compiler is telling you that it doesn't exist. And it is right as always.
    variable teams is only visible and accessible in the Championship class.

    Therefore, you can do one of two things; create a method with the for each loop inside the Championship class to print the standings

    || create a getter method for the teams in the championship class and use it to get the teams of that Championship instance. e.g for (Team t : getTeams())

  15. #15
    ahanslot is offline Member
    Join Date
    Sep 2013
    Posts
    26
    Rep Power
    0

    Default Re: Comparable and Iterable Interface

    Quote Originally Posted by superhaNds View Post
    ok, I assume that you tried using 'teams' in the loop and as expected the compiler is telling you that it doesn't exist. And it is right as always.
    variable teams is only visible and accessible in the Championship class.

    Therefore, you can do one of two things; create a method with the for each loop inside the Championship class to print the standings

    || create a getter method for the teams in the championship class and use it to get the teams of that Championship instance. e.g for (Team t : getTeams())
    I have to stick to the diagram in the first post, I have already created a get method in the championship class and this returns the team at i.

    I have tried in my testing class System.out.println("1:" + formula1.get(0)); System.out.println("2:" + formula1.get(1)); System.out.println("2:" + formula1.get(2));

    Java Code:
    //get team
    	public Team get(int i) {
            Team t = null;
            if (0 <= i && i < teams.size()) {
                t = teams.get(i);
            } else {
                t = null; // i is out of range
            }
            return t;
        }
    this successfully prints out the teams but I have to write a statement for each, it it possible to use this get method and the for each loop to:

    Output in order the championship standings including team name, and points, as well as the full name of each driver within the team and their respective points. ?

    thanks

  16. #16
    superhaNds is offline Senior Member
    Join Date
    Apr 2013
    Location
    Sweden
    Posts
    268
    Rep Power
    2

    Default Re: Comparable and Iterable Interface

    you misunderstood. get team at i is one thing, getTeams as to return the whole list is another thing. Why won't you make that method with the loop inside the champiosnhip class

  17. #17
    ahanslot is offline Member
    Join Date
    Sep 2013
    Posts
    26
    Rep Power
    0

    Default Re: Comparable and Iterable Interface

    I have to follow the specification diagram strictly and I do not think I can add additional methods :(

  18. #18
    superhaNds is offline Senior Member
    Join Date
    Apr 2013
    Location
    Sweden
    Posts
    268
    Rep Power
    2

    Default Re: Comparable and Iterable Interface

    If you can't get the teams of the championship using a get method then you can't make that loop outside the class unless you change the accessibility of the variable (public or none)
    which is not good.

    I do not think a simple get method would get you in trouble but if you don't want to, don't.

    You can use the iterator ;

    Java Code:
    for (Iterator<Team> x = championship.iterator(); x.hasNext(); )
            x.next().toString();

  19. #19
    ahanslot is offline Member
    Join Date
    Sep 2013
    Posts
    26
    Rep Power
    0

    Default Re: Comparable and Iterable Interface

    Quote Originally Posted by superhaNds View Post
    If you can't get the teams of the championship using a get method then you can't make that loop outside the class unless you change the accessibility of the variable (public or none)
    which is not good.

    I do not think a simple get method would get you in trouble but if you don't want to, don't.

    You can use the iterator ;

    Java Code:
    for (Iterator<Team> x = championship.iterator(); x.hasNext(); )
            x.next().toString();
    Thanks for the reply i went through all the comments and got the following to work:

    Java Code:
    for (Team str: formula1)
    		{
    			//System.out.println(str.getDriver1().getDetails().getFullName());
    			System.out.println(str.getName()+" " + str.getPoints() + " " + str.getDriver1().getDetails().getFullName() + " "+ str.getDriver1().getPoints() + " " + str.getDriver2().getDetails().getFullName() + " "+str.getDriver2().getPoints());
    		}}
    I also want to Calculate the total combined salary for all mechanics and drivers belonging to the current
    championship leading team, and output this figure, along with the number of team members.

    I have used:

    Java Code:
    for (Mechanic str1: formula1.get(0)){
    			System.out.println(str1.getSalary());
    		}
    this gets the mechanics salary for the leading lead, how can I add these together and also retrieve the salary for driver1 + 2 and add their salary?
    Last edited by ahanslot; 01-06-2014 at 02:47 PM.

  20. #20
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,783
    Blog Entries
    7
    Rep Power
    21

    Default Re: Comparable and Iterable Interface

    Quote Originally Posted by ahanslot View Post
    Thanks for the reply i went through all the comments and got the following to work:

    Java Code:
    for (Team str: formula1)
    		{
    			//System.out.println(str.getDriver1().getDetails().getFullName());
    			System.out.println(str.getName()+" " + str.getPoints() + " " + str.getDriver1().getDetails().getFullName() + " "+ str.getDriver1().getPoints() + " " + str.getDriver2().getDetails().getFullName() + " "+str.getDriver2().getPoints());
    		}}
    That rather long list of String concatenations is an ideal candidate for the toString() method in the Team class ...

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

Similar Threads

  1. again the Comparable interface
    By willemjav in forum Advanced Java
    Replies: 11
    Last Post: 07-09-2013, 02:59 PM
  2. Comparable interface
    By diamonddragon in forum New To Java
    Replies: 17
    Last Post: 02-01-2012, 01:07 AM
  3. Implement Comparable interface
    By JojoDiaz in forum New To Java
    Replies: 3
    Last Post: 11-07-2011, 08:10 AM
  4. Comparable Interface
    By Yelrubk in forum New To Java
    Replies: 3
    Last Post: 04-28-2010, 03:46 PM
  5. interface Comparable<T> problem
    By Lennon-Guru in forum New To Java
    Replies: 3
    Last Post: 03-05-2008, 01:17 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •