Answered step by step
Verified Expert Solution
Question
1 Approved Answer
Instructions A farmer has an ArrayList of Pigs (fat pigs, if you are wondering). He wants to be able to sort the pigs by Weight
Instructions A farmer has an ArrayList of Pigs (fat pigs, if you are wondering). He wants to be able to sort the pigs by Weight and Age. He is a smart man and will not reinvent the wheel by writing a sorting algorithm. He knows that he can sort his ArrayList using the Collections.sort() static method. The problem is that Java is not that clever. Although Java knows the sorting algorithm it does not know how to compare two pigs =/ Your job is to help the farmer by implementing the Comparable interface (type-safe, we talked (will talk) about in Lecture 14) in the Pigs class. Pigs should be compared by weight ("smallest" first). If both pigs have the same weight, then compare them by age (youngest first). The starter code will not compile until you implement the Comparable interface on the Pig class. You can/should play with the implementation of comparable to see how it affects the sorting. Pig.java PigsPigsPigs.java + New 1- public class Pig { 2 private int age; 3 private int weight; 4 5 6- public Pig(int age, int weight) { 7 this.age = age; 8 this.weight weight; 9 } 10 11 public int getAge() { 12 return age; 13 } 14 15 @Override 16- public String toString() { 17 return String.format("Age: %d, weight: %d kg", age, weight); 18 } 19 20 } 21 | Pig.java PigsPigs Pigs.java + New 1 //Do not modify this file. The farmer will be sad and your test cases will fail :) 2 3- import java.util.ArrayList; 4 import java.util.Collections; 5 6- public class PigsPigsPigs { 7- public static void main(String[] args) { 8 ArrayList fatPigs = new ArrayList(); 9 fatPigs.add(new Pig(4,300)); 10 fatPigs.add(new Pig(6,278)); 11 fatPigs.add(new Pig(4,100)); 12 fatPigs.add(new Pig(3,500)); 13 fatPigs.add(new Pig(6,5000)); 14 fatPigs.add(new Pig(1,20)); 15 fatPigs.add(new Pig(1,500)); 16 fatPigs.add(new Pig(8,500)); 17 18 Collections. sort(fatPigs); 19 20 for (Pig pig: fatPigs) { 21 System.out.println(pig); 22 } 23 24 25 } 26 }
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