Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

In class we\'re working with ADTs in Java. I\'m wondering how to sort a collecti

ID: 3674070 • Letter: I

Question

In class we're working with ADTs in Java. I'm wondering how to sort a collection of packets in ascending order (each package contains an int value) without using the Collections.sort() method.

Explanation / Answer

import java.util.*; public class Person implements Comparable { String name; int age; public Person(String name,int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } public String toString() { return name +" : "+ age; } /* ** Implement the natural order for this class */ public int compareTo(Person p) { return getName().compareTo(p.getName()); } static class AgeComparator implements Comparator { publicint compare(Person p1,Person p2) { int age1 = p1.getAge(); int age2 = p2.getAge(); if(age1 == age2) return0; elseif(age1 > age2) return1; elsereturn-1; } } public static void main(String[] args) { List people =newArrayList(); people.add(newPerson("Homer",38)); people.add(newPerson("Marge",35)); people.add(newPerson("Bart",15)); people.add(newPerson("Lisa",13));// Sort by natural orderCollections.sort(people); System.out.println("Sort by Natural order"); System.out.println(" "+ people);// Sort by reverse natural orderCollections.sort(people,Collections.reverseOrder()); System.out.println("Sort by reverse natural order"); System.out.println(" "+ people);// Use a Comparator to sort by ageCollections.sort(people,newPerson.AgeComparator()); System.out.println("Sort using Age Comparator"); System.out.println(" "+ people);// Use a Comparator to sort by descending ageCollections.sort(people,Collections.reverseOrder(newPerson.AgeComparator())); System.out.println("Sort using Reverse Age Comparator"); System.out.println(" "+ people); } }
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote