java - Generic Method to find the median of 3 values -


i needed method median of 3 values, thought opportunity write generic method since don't have practiced. wrote , seems pretty straight-forward, though warning, seems work fine, according tests.

i'm aware use inherently sorted set, or collections.sort(), approach sake of understanding.

i want pinpoint few things:

  1. i noticed doesn't work if tried declare medianhelper arrays.aslist(a, b, c) why this? trying search gives me unrelated results , it's otherwise elusive since i'm not sure happening. unsupportedoperationexception, not present way have below.
  2. why getting warning? wrong/missing?

the method follows:

private static <t extends comparable> t median(t a, t b, t c) {     list<t> medianhelper = new arraylist<>();     t max;     t min;      medianhelper.add(a);     medianhelper.add(b);     medianhelper.add(c);      if (a.compareto(b) >= 0) {         max = a;         min = b;     } else {         max = b;         min = a;     }      if (max.compareto(c) == -1) {         max = c;     }      if (min.compareto(c) >= 0) {         min = c;     }      medianhelper.remove(max);     medianhelper.remove(min);      return medianhelper.get(0); } 

you haven't correctly introduced type-parameter t, comparable generic, too.

it should rather be:

private static <t extends comparable<? super t>> t median(t a, t b, t c)  

furthermore, can sort medianhelper list, since elements will comparable. method can shortened to:

private static <t extends comparable<? super t>> t median(t a, t b, t c) {     list<t> medianhelper = arrays.aslist(a, b, c);      collections.sort(medianhelper);      return medianhelper.get(1); } 

note arrays.aslist() returns unmodifiable list, means you're not allowed add/remove elements after it's created. if wish comparisons yourself, can use new arraylist<> instead of arrays.aslist() , manually add elements it.


Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -