2011-05-11 35 views
0

在这里,我试图用这个getSmallestValue方法来整理intV和stringV。尝试了不同的想法,但似乎没有工作。任何人有任何明智的想法如何实现这个getSmallestValue方法?可比较的类型在矢量整数或字符串中排序

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); 
    } 
} 
+0

如果您在调试器中逐步了解代码,则会出现几个错误。 ;) – 2011-05-11 10:29:52

+0

几个警告即将到来。但在此刻,重点是让代码能够很容易地工作。我知道代码是错误的,但它编译。 – Splitter 2011-05-11 10:34:24

回答

2

欢迎来到StackOverflow。

你的基本问题是你试图把一个Vector变成一个你不能做的Integer。

可能更有用的是使用矢量的第一个元素。

我建议你

  • 使用列表,而不是载体。
  • 我不会使用手动包装
  • 使用泛型定义getSmallestValue以避免混淆。

这里有两种方法可以实现这种方法。

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); 
+0

是啊列表更容易做到这一点我做到了这一点。但我想知道的是如何在向量或ArrayList中执行此操作。 – Splitter 2011-05-11 10:43:01

+0

'Vector'和'ArrayList'都是'List'没有区别。 – 2011-05-11 10:44:35

+0

完美的答案你得到了彼得。谢谢 – Splitter 2011-05-11 11:10:52

0

使用Collections.min()。你可以检查出source如果你想知道它是如何实现的。

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

不工作仍然队友这个错误出现线程“main”中的异常java.lang.ClassCastException:java.util.Vector不能转换为java.lang.Comparable \t at test.getSmallestValue(test.java:17) \t at test.main(test.java:27) – Splitter 2011-05-11 10:36:38

+1

不要使用getSmallestValue函数,而应使用Collections.min – Emil 2011-05-11 10:38:22

+0

@Spiltter,这是因为您试图将版本转换为整型。我的猜测是你正在调用'min()',但忽略结果? – 2011-05-11 10:39:11