java - Comparable type Sorting in a Vector int or String -
in trying sort out intv , stringv using getsmallestvalue method. tried different ideas not seems working. have bright ideas how implement getsmallestvalue method?
public class test { public static comparable getsmallestvalue(vector<comparable> a) { comparator com = collections.reverseorder(); collections.sort(a, com); return (comparable) a; } public static void main(string[] args) { vector<comparable> intv = new vector<comparable>(); intv.add(new integer(-1)); intv.add(new integer(56)); intv.add(new integer(-100)); int smallestint = (integer) getsmallestvalue(intv); system.out.println(smallestint); vector<comparable> stringv = new vector<comparable>(); stringv.add("testing"); stringv.add("pti"); stringv.add("semestergoes"); string smalleststring = (string) getsmallestvalue(stringv); system.out.println(smalleststring); } }
welcome stackoverflow.
your basic problem have tried turn vector integer cannot do.
what more useful use first element of vector.
i suggest
- use list instead of vector.
- i wouldn't use manual wrapping
- define getsmallestvalue using generics avoid confusion.
here 2 ways implement method.
public static <n extends comparable<n>> n getsmallestvalue(list<n> a) { collections.sort(a); return a.get(0); } public static <n extends comparable<n>> n getsmallestvalue2(list<n> a) { return collections.min(a); } list<integer> ints = arrays.aslist(-1, 56, -100); int min = getsmallestvalue(ints); // or int min = collections.min(ints);
Comments
Post a Comment