Question
Hi! I have two classes , Recipe class for instansiate, RecipeList class to store Recipes in ArrayList. How to I make compareTo method for RecipeList?
Hi! I have two classes , Recipe class for instansiate, RecipeList class to store Recipes in ArrayList. How to I make compareTo method for RecipeList?
In main method class, I want to sort Recipes for alphabetical order..
public class Recipe { private String name; private String ingredients; private String instructions; public Recipe (String name, String ingredients, String instructions){ this.name=name; this.ingredients = ingredients; this.instructions = instructions; } public void setName(String name){ this.name = name; } public String getName(){ return name; } public void setIngredients(String ingredients){ this.ingredients = ingredients; } public String getIngredients(){ return ingredients; } public void setInstructions(String instructions){ this.instructions = instructions; } public String getInstructions(){ return instructions; } public String toString() { return "Recipe name: " + this.name + "Ingredients: " + this.ingredients + "Instructions: "+ this.instructions; } public int compareTo(Recipe otherRecipe) { if(this.getName().toUpperCase().compareTo(otherRecipe.getName().toUpperCase()) return -1; } else if(this.getName().toUpperCase().compareTo(otherRecipe.getName().toUpperCase())>0){ return 1; }else { return 0; } }
}
--------------------------------------------------------------------------------------------
import java.util.ArrayList;
public class RecipeList implements Comparable{ ArrayList recipes; private Recipe recipe; public RecipeList (){ this.recipes = new ArrayList(); }
@Override
public int compareTo(Recipe otherRecipe) { //TO-DO return 0; } }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started