Please write in Java code. Thanks 1. Given the Item class below, implement the C
ID: 3861931 • Letter: P
Question
Please write in Java code. Thanks
1. Given the Item class below, implement the Comparable interface so two Item objects can be compared. Two Item objects should be compared first by weight, then by height if the weights are the same.
public class Item {
private int weight;
private int height;
// Assume constructors, gets, sets, etc. already exist.
// Write the code to compare two Items based on the directions above:
2. Write the selectionSort method as it appears in your utility class:
3. Write the code to call selectionSort (in your utility class) for this array:
// Add code to call selectionSort from your utility class
}
4. Explain ‘static’ as used in a Java program.
5. In the Java statement below, what is meant by the keyword ‘this’?
6. Create a method named reverseArray that:
-accepts an array of doubles,
-reverses the contents of the array
7. Given the simple version of the Student class as presented in lectures, write the equals method and the toString method:
Explanation / Answer
1.
public class Item implements Comparable<Item>{
public Item(int weight, int height) {
this.weight = weight;
this.height = height;
}
private int weight;
private int height;
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public int compareInt(int a, int b)
{
if (a > b) return -1;
if (a < b) return 1;
return 0;
}
@Override
public int compareTo(Item o) {
if (getWeight() == o.getWeight())
{
return compareInt(getHeight(), o.getHeight());
}
return compareInt(getWeight(), o.getWeight());
}
// Assume constructors, gets, sets, etc. already exist.
// Write the code to compare two Items based on the directions above:
}// end class Item