JAVA Need code for compare method for override import java.util.*; @SuppressWarn
ID: 3802341 • Letter: J
Question
JAVA
Need code for compare method for override
import java.util.*;
@SuppressWarnings("rawtypes")
public class Table implements Iterable<Comparable[]> {
private Comparable data[][];
// Creates a table that is a copy of the given input array
public Table(Comparable data[][]) {
int rows = data.length;
int cols = 0;
if (rows > 0) cols = data[0].length;
this.data = new Comparable[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
this.data[i][j] = data[i][j];
}
}
}
// Comparator class for comparing with respect to a single column
public static class ByColumn implements Comparator<Comparable[]> {
public ByColumn(int col, boolean ascending) {
ascending = true;
for(int i = 0; i < data.length-1; i++) {
if(data[i] >= data[i+1]);
ascending = false;
}
@Override
public int compare(Comparable[] o1, Comparable[] o2) {
// TODO
return 0;
}
}
Explanation / Answer
Ans: I inserted the code for overriding.
import java.util.*;
@SuppressWarnings("rawtypes")
public class Table implements Iterable<Comparable[]> {
private Comparable data[][];
// Creates a table that is a copy of the given input array
public Table(Comparable data[][]) {
int rows = data.length;
int cols = 0;
if (rows > 0) cols = data[0].length;
this.data = new Comparable[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
this.data[i][j] = data[i][j];
}
}
}
// Comparator class for comparing with respect to a single column
public static class ByColumn implements Comparator<Comparable[]> {
public ByColumn(int col, boolean ascending) {
ascending = true;
for(int i = 0; i < data.length-1; i++) {
if(data[i] >= data[i+1]);
ascending = false;
}
@Override
public int compare(Comparable[] o1, Comparable[] o2) {
// this is the code i wrote for override using comparable
Comparable o1Comparable = getComparable(o1);
Comparable o2Comparable = getComparable(o2);
return o1Comparable.compareTo(o2Comparable);
}
@SuppressWarnings("rawtypes")
private Comparable getComparable(Object o) {
try {
Object invoke = o.getClass().getMethod(property, new Class[] {})
.invoke(o, new Class[] {});
return ((Comparable)invoke);
} catch (Exception e) {
throw new IllegalArgumentException(e.getMessage());
}
}
return 0;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.