PLease help i need this in java please also explain what how the comparable inte
ID: 3790487 • Letter: P
Question
PLease help i need this in java please also explain what how the comparable interface works and also how a compareTo method works
Have the AList class implement the Comparable interface. Write the compareTo method to order lists this way:
first by size: a list that has fewer elements is smaller
second, if the lists have the same number of elements: order by how many elements in the matching index of the other list are smaller; the list with more smaller elements in the matching position is smaller (see the examples below)
Note, to test your AList class, use these class and method headers:
public class AList<T extends Comparable> implements ListInterface<T>, Comparable<AList<T>>
public int compareTo(AList<T> otherList)
You also need to change the lines in the constructor and toArray methods from using Object to using Comparable:
T[] tempList = (T[]) new Comparable[initialCapacity + 1];
T[] result = (T[]) new Comparable[numberOfEntries]; // Unchecked cast
Example:
List A: 1, 5, 6, 8, 10
List B: 2, 4, 3, 9, 7
In this example, List B is smaller because 3/5 elements in List B are less than their matching element in List A (4 < 5, 3 < 6, and 7 < 10).
List A: 1, 3, 5, 7, 10
List B: 2, 4, 3, 9, 7
In this example, List A is smaller because 3/5 elements in List A are less than their matching element in List B 1 < 2, 3 < 4, and 7 < 9).
List A: 1, 2, 3, 10, 9
List B: 2, 4, 3, 9, 7
In this example, neither is smaller because each has 2/5 elements smaller than their matching element in the other list.
Explanation / Answer
Hi, Please find implementation.
Plese let me know in case of any issue.
public class AList<T extends Comparable> implements ListInterface<T>, Comparable<AList<T>>{
@Override
public int compareTo(AList<T> o) {
if(this.size() < o.size())
return -1;
if(this.size() > o.size())
return 1;
else{
int aSmallest = 0;
int bSmallest = 0;
for(int i=0; i<size(); i++){
if(get(i) < o.get(i))
aSmallest++;
else if(get(i) > o.get(i))
bSmallest++;
}
if(aSmallest > bSmallest)
return -1;
else if(aSmallest < bSmallest)
return 1;
else
return 0;
}
}
}
/*
Hi friend, you have not posted ListInterface methods, so i do bot know what are the methods to
get an element at index 'i' and what is the method to get size of list
I have assumed that: get(int index): returns the element at index 'i
size() : method to return size of list
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.