问题描述
嘿,我正在尝试实现ShellSort算法,现在遇到了一个问题:
Hey, I'm trying to implement the ShellSort algorithm and now I got a problem:
警告:[unchecked] unchecked cast
找到:java.util.Vector
必需:java。 util.Vector< java.lang.Object>
Vector< Object> vcur =(Vector< Object>)currentCols [tcur];
与 vtmp
相同。
我不知道问题出在哪里。如果您能帮助我,那真是太好了。 :)
这是我的代码:
I don't know where the problem is. It would be really great if you could help me. :)
This is my code:
public static Vector<Object> shellSort(Vector<Object> ul) {
int lcount = ul.size();
int colcount = 4; // 2^x
Vector[] currentCols = { ul };
for(; colcount > 0; colcount = (colcount / 2)) {
Vector[] tmpCols = new Vector[colcount];
for(int t1 = 0; t1 < colcount; t1++) {
tmpCols[t1] = new Vector<Object>();
}
int tcur = 0;
int tcurlvl = 0;
int ttmp = 0;
for(int t2 = 0; t2 < lcount; t2++) {
Vector<Object> vcur = (Vector<Object>)currentCols[tcur];
Vector<Object> vtmp = (Vector<Object>)tmpCols[ttmp];
vtmp.addElement((Object)vcur.elementAt(tcurlvl));
// step to next place
tcur++;
ttmp++;
if(tcur == currentCols.length) { tcur = 0; tcurlvl++; }
if(ttmp == tmpCols.length) { ttmp = 0; }
}
}
return ul;
}
推荐答案
这仍然无法解决问题(您的代码无法使用...永不排序),但已更新为使用List而不是Vector(Vector已过时,由于官方API依赖于此,因此不建议弃用)。除非您需要Vector内置的同步,否则请使用List / ArrayList。
This still won't fix the issue (you code doesn't work... never sorts) but it is updated to use List instead of Vector (Vector is obsolete, cannot be deprecated since official APIs depend on it). Unless you need the synchronization built into Vector use List/ArrayList instead.
我还更改了数组的创建方式,使其更接近于泛型(不能真正地进行泛型数组的创建)。
I also changed the array creation to be closer to generic (cannot truly do generic array creation).
最后,我使整个方法通用,以便它可以与对象(而不是对象)(例如列表或列表等)以外的其他类型一起安全地使用。
Finally I made the whole method generic so that it can work typesafely with things other than Object (so a List or List, etc...).
尽管它仍然会发出警告。也许您应该在担心此特定警告之前就努力使代码正常工作(通常我不建议这样做,但是使用泛型有时可能是一种更好的方法)。
It still gives warnings though. Perhaps you should work on getting the code to work properly before you worry about this particular warning (normally I would not suggest that, but with generics that can sometimes be a better way to do it).
public static <T> List<T> shellSort(List<T> ul)
{
int lcount = ul.size();
int colcount = 4; // 2^x
List<T>[] currentCols = (List<T>[])Array.newInstance(List.class, 1);
currentCols[0] = ul;
for(; colcount > 0; colcount = (colcount / 2))
{
List<T>[] tmpCols = (List<T>[])Array.newInstance(List.class, colcount);
for(int t1 = 0; t1 < colcount; t1++)
{
tmpCols[t1] = new ArrayList<T>();
}
int tcur = 0;
int tcurlvl = 0;
int ttmp = 0;
for(int t2 = 0; t2 < lcount; t2++)
{
List<T> vcur = currentCols[tcur];
List<T> vtmp = tmpCols[ttmp];
vtmp.add(vcur.get(tcurlvl));
// step to next place
tcur++;
ttmp++;
if(tcur == currentCols.length) { tcur = 0; tcurlvl++; }
if(ttmp == tmpCols.length) { ttmp = 0; }
}
}
return ul;
}
这篇关于未经检查的转换问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!