java - Questions about implementing the Comparable interface -
i teaching java programming class first time. textbook uses comparable
, see examples on net use comparable<t>
. these using 2 different interfaces?
related this, when write compareto() method in student class, textbook uses
public int compareto(object other){ if (! (other instance of student)) throw new illegalargumentexception("parameter must student"); return name.compareto( ((student)other).getname() ); }
i see other examples of compareto() this:
public int compareto(student otherstudent){ return name.compareto( otherstudent.getname() ); }
is second construct 1 should use if student class implements comparable<student>
?
finally, textbook gives hints on how write general-purpose object sorting algorithm. arrived @ following. works, gives "unchecked or unsafe operations" warning. there way write "safe" general-purpose sorting algorithm?
private static void bubblesortobjects(comparable[] array) { int = 0; boolean swapped = true; while (swapped && < array.length - 1) { i++; swapped = false; (int j = 0; j < array.length - i; j++) { if (array[j].compareto(array[j + 1]) > 0) { comparable temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; swapped = true; } } } }
thanks or advice.
just help, modern general purpose sorting algorithm be:
private static <t extends comparable<? super t>> void bubblesortobjects(t[] array) { int = 0; boolean swapped = true; while (swapped && < array.length - 1) { i++; swapped = false; (int j = 0; j < array.length - i; j++) { if (array[j].compareto(array[j + 1]) > 0) { t temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; swapped = true; } } } }
Comments
Post a Comment