这里有一个使用ArrayList选择排序的例子,Vector的用法和ArrayList基本一样,都属于List下的容器类.两者的区别是:Vector同步,线程安全,不允许空元素,ArrayList非同步,线程不安全,允许空元素.具体的使用上的差别,可以参阅jdk api文档.import java.util.*;class InsertSort {
ArrayList al;
public InsertSort(int num, int mod) {
al = new ArrayList(num);
Random rand = new Random();
System.out.println("The ArrayList Sort Before:");
for (int i = 0; i < num; i++) {
al.add(new Integer(Math.abs(rand.nextInt()) % mod + 1));
System.out.println("al[" + i + "]=" + al.get(i));
}
} public void SortIt() {
Integer tempInt;
int MaxSize = 1;
for (int i = 1; i < al.size(); i++) {
tempInt = (Integer) al.remove(i);
if (tempInt.intValue() >= ( (Integer) al.get(MaxSize - 1)).intValue()) {
al.add(MaxSize, tempInt);
MaxSize++;
System.out.println(al.toString());
}
else {
for (int j = 0; j < MaxSize; j++) {
if ( ( (Integer) al.get(j)).intValue() >= tempInt.intValue()) {
al.add(j, tempInt);
MaxSize++;
System.out.println(al.toString());
break;
}
}
}
}
System.out.println("The ArrayList Sort After:");
for (int i = 0; i < al.size(); i++) {
System.out.println("al[" + i + "]=" + al.get(i));
}
} public static void main(String[] args) {
InsertSort is = new InsertSort(10, 100);
is.SortIt();
}
}
ArrayList al;
public InsertSort(int num, int mod) {
al = new ArrayList(num);
Random rand = new Random();
System.out.println("The ArrayList Sort Before:");
for (int i = 0; i < num; i++) {
al.add(new Integer(Math.abs(rand.nextInt()) % mod + 1));
System.out.println("al[" + i + "]=" + al.get(i));
}
} public void SortIt() {
Integer tempInt;
int MaxSize = 1;
for (int i = 1; i < al.size(); i++) {
tempInt = (Integer) al.remove(i);
if (tempInt.intValue() >= ( (Integer) al.get(MaxSize - 1)).intValue()) {
al.add(MaxSize, tempInt);
MaxSize++;
System.out.println(al.toString());
}
else {
for (int j = 0; j < MaxSize; j++) {
if ( ( (Integer) al.get(j)).intValue() >= tempInt.intValue()) {
al.add(j, tempInt);
MaxSize++;
System.out.println(al.toString());
break;
}
}
}
}
System.out.println("The ArrayList Sort After:");
for (int i = 0; i < al.size(); i++) {
System.out.println("al[" + i + "]=" + al.get(i));
}
} public static void main(String[] args) {
InsertSort is = new InsertSort(10, 100);
is.SortIt();
}
}
解决方案 »
- 求编程
- 求助,谁用过display标签,display标签分页问题?
- struts 标签
- 各位能否说说spring和struts的区别,在spring中有struts的重复提交问题吗?
- webwork中怎么在interceptor中得到正运行的action 的名字???
- 为何apache+resin对JAVA不支持?
- 高分求教!!!
- webapplication的验证问题
- XML解析错误
- 关于在weblogic7中显示中文的问题!
- tomcat 5与SQL2000,何配置与使用连接池
- 我在JBX中写了个JSP页面,用的是JBX自带的tomcat服务器,启动服务后在IE中输入http://localhost:8080/test/index.jsp或者http://127.0.0.
v是Vector对象
这句话就可以完成排序了