开发者

Comparable type Sorting in a Vector int or String

In this I am trying to sort out the intV and stringV using this getSmallestValue method. Tried different ideas but does not seems to be working. Anyone have any bright ideas how to implement this 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");
    开发者_JAVA技巧    stringV.add("semesterGoes");
        String smallestString = (String) getSmallestValue(stringV);

        System.out.println(smallestString);
    }
}


Welcome to StackOverflow.

Your basic problem is that you have tried to turn a Vector into an Integer which you cannot do.

What is likely to be more useful is to use the first element of the vector.

I would suggest you

  • use List instead of Vector.
  • I wouldn't use manual wrapping
  • define the getSmallestValue using generics to avoid confusion.

Here are two ways you could implement this 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);


Use Collections.min().You can check out the source if you you want to know how it's implemented.

Vector<Integer> v=new Vector<Integer>();
v.add(22);v.add(33);
System.out.println(Collections.min(v));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜