Write below code in Java The Java library contains an interface called Comparabl
ID: 3664714 • Letter: W
Question
Write below code in Java
The Java library contains an interface called Comparable that is defined as follows:
public interface Comparable<T>
{
intcompareTo(T o);
}
The variable T is called a generic type and can represent any object type (e.g., String, Cat, whatever). The only thing that it can’t represent is primitive datatypes. This is exactly the same concept as we saw when we studied the ArrayList<T> class. The point of this interface is to define a uniform way of designing classes in which any two object can be compared (i.e. for any two objects x and y of the class, either x is less than y, x is greater than y, or x is equal to y). A class should implement this method so that whenever one calls x.compareTo(y)for objects x and y, the method returns a negative integer if x is less than y, zero if x is equal to y, and a positive integer is x is greater than y. Given an array of typeT (or an ArrayList<T>), calling Arrays.sort(T[] array) (or respectively Collections.sort(ArrayList<T> list) for an ArrayList) will invoke the compareTo method of the underlying class type to compare elements of the array/ArrayList pairwise in order to perform the sorting. You can check out Oracle’s documentation on this interface athttps://docs.oracle.com/javase/8/docs/api/java/lang/Comparable.html#compareTo-T- for more information.
For this exercise, I want you to take the Bug class from HW1 and modify it so that it implements the Comparable<Bug> interface. The compareTo method should compare two bugs Bug1 and Bug2 as follows:
Bug1 is considered larger than Bug2 if either
(1) Bug1’s Manhattan distance from the origin, i.e. |xpos| + |ypos| where |.| is the absolute value operation, is larger than Bug2’s Manhattan distance from the origin, OR
(2) Bug1’s Manhattan distance from the origin is equal to Bug2’s Manhattan distance from the origin and Bug1’s direction is closer to North than Bug2’s direction moving counter-clockwise (i.e., North > East > South > West).
Bug1 and Bug2 are considered the same if their Manhattan distances from the origin are equal and their directions are the same. (Note that this does not necessarily imply that Bug1 and Bug2 are in the same exact position. For example, a Bug at (xpos = 1, ypos = 1, dir = North) and a Bug at (xpos = -1, ypos = 1, dir = North) are considered equivalent according to the metric above.
a. Rewrite your Bug class from Homework1 so that it implements the Comparable<Bug> interface as described above.
Howework1:
Write a class Bug that models a bug moving in the x-y plane. The bug either moves north, east, south, or west. Initially, the bug moves to the north, but it can turn to the right or the left by 90 degrees at a time. In each move, its position changes by one unit in the current direction. Provide a constructor
public Bug(intinitX, intinitY) // places the bug at initial position
// initX, initY
and methods:
public void turnRight() // turn right by 90 degrees
public void turnLeft() // turn left by 90 degrees
public void move() // move in current direction by 1 unit
publicintgetPositionX() // get X position
publicintgetPositionY() // get Y position
public String getDirection() // returns the direction (e.g. “east”)
Also, you must override the method public String toString() so that it returns a string that displays the bug’s position (x and y coordinates) as well as the direction that it is currently facing. Note: you don’t need to draw the bug on the screen (we have not learned how to do this yet). You just need the bug object to keep track of its current position and direction.
b. Write a tester class with a main method that initializes an ArrayList<Bug> of Bug objects with randomly selected positions and directions. Then use the Collections.sort method (described here: http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html) to sort this ArrayList. Use enhanced for loops to print out the original ArrayList and the sorted ArrayList.
Explanation / Answer
import static java.lang.Math.abs;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author PINERONE
*/
public class TestBugs {
ArrayList<Bug> bug;
public TestBugs(int element){
bug = new ArrayList<>(element);
loadList(element);
}
private void loadList(int element){
Bug b;
Random rnd = new Random();
int PosX;
int PosY;
int d;
String dir;
for(int i=0; i<element; i++){
PosX = (int)(rnd.nextDouble() * 5);
PosY = (int)(rnd.nextDouble() * 5);
d = (int)(rnd.nextDouble() * 4); //direction
switch (d){
case 0 : dir = "North"; break;
case 1 : dir = "East"; break;
case 2 : dir = "South"; break;
default : dir = "West"; break;
}
b = new Bug(PosX, PosY, dir);
bug.add(b);
}
}
public void PrintList(){
for (int i=0; i<bug.size(); i++){
System.out.println("b"+i+": " +bug.get(i).ToString());
}
}
public void Sort(){
Collections.sort((ArrayList<Bug>) bug);
}
public static void main(String[] args) {
// TODO code application logic here
TestBugs tb = new TestBugs(10);
System.out.println("Before Sorting:");
tb.PrintList();
tb.Sort();
System.out.println("after Sorting:");
tb.PrintList();
}
}
// class Bug
class Bug implements Comparable<Bug>{
private int x;
private int y;
private String dir;
public Bug(){
x=0;
y=0;
dir="North";
}
public Bug(int x, int y, String dir){
this.x = x;
this.y = y;
this.dir = dir;
}
public String ToString(){
return "Direction = "+dir+", PosX = "+x+", PosY = "+y;
}
private int ClockWise(){
int clockwise = 0;
switch (dir){
case "North" : clockwise = 0; break;
case "East" : clockwise = -1; break;
case "South" : clockwise = -2; break;
default : clockwise = -3; break;
}
return clockwise;
}
@Override
public int compareTo(Bug o) {
int dThis = abs(this.x)+abs(this.y);
int dO = abs(o.x)+abs(o.y);
if (dThis > dO){
return 1;
}else
if (dThis < dO){
return -1;
}else
if (this.ClockWise() > o.ClockWise())
return 1;
else
if (this.ClockWise() < o.ClockWise())
return -1;
return 0;
}
public void turnRight(){
switch (dir){
case "North" : dir = "East"; break;
case "East" : dir = "South"; break;
case "South" : dir = "West"; break;
default : dir = "North"; break;
}
}
public void turnLeft(){
switch (dir){
case "North" : dir = "West"; break;
case "East" : dir = "North"; break;
case "South" : dir = "East"; break;
default : dir = "South"; break;
}
}
public void move(){
switch (dir){
case "North" : y++; break;
case "East" : x++; break;
case "South" : y--; break;
default : x--; break;
}
}
public int getPositionX(){
return x;
}
public int getPositionY(){
return y;
}
public String getDirection(){
return dir;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.