JAVA实验报告六
1.Eclipse环境下,输入例13.6(第2版或第3版),调试运行输出结果。
2.利用LinkedList和ArrayList的相关知识,分别编程实现如下功能:
(1)初始化链表list,存放字符串数据“Java”、“真”、“有趣”、“!”;
(2)用迭代器方法和for-get方法遍历输出list中的全部数据;
(3)比较不同遍历方法的运行时间;
(4)编写main方法,测试上述代码的功能。
(用自然语言或算法流程图的形式表达算法设计思想与算法实现步骤,注意不是贴源代码,百度搜索相关学习资料)
一、
1、新建包,在包中建类Example13_6,并建立main函数;
2、新建栈stack,向栈中压入两个数据1;
3、把栈中的数据取数来求和输出并存入栈中,然后再存入前一个数据,这样重复10次。
二、
1、新建包,在包中建类Example6_2,并建立main函数;
2、新建泛型LinkedList的对象list,往里面添加题目要求的数据,建立迭代器,在遍历前取当前时间,再用迭代器遍历之后再取当前时间,用后者减去前者得到遍历时间并输出;然后使用for循环利用get()方法遍历并输出所需时间;
3、新建泛型LinkedList的对象list1,往里面添加题目要求的数据,建立迭代器,在遍历前取当前时间,再用迭代器遍历之后再取当前时间,用后者减去前者得到遍历时间并输出;然后使用for循环利用get()方法遍历并输出所需时间;
Example13_6.java
import java.util. *;
public class Example13_6 {
public static void main(String[] args) {
Stack<Integer>stack=new Stack<Integer>();
stack.push(new Integer(1));
stack.push(new Integer(1));
int k=1;
while(k<=10) {
for(int i=1;i<=2;i++) {
Integer F1=stack.pop();
int f1=F1.intValue();
Integer F2=stack.pop();
int f2=F2.intValue();
Integer temp=new Integer(f1+f2);
System.out.println(""+temp.toString());
stack.push(temp);
stack.push(F2);
k++;
}
}
}
}
Example6_2.java
import java.util.*;
public class Question6_2 {
public static void main(String[] args) {
LinkedList<String> list=new LinkedList<String>();
list.add("Java");
list.add("真");
list.add("有趣");
list.add("!");
//迭代器方法遍历输出list中的全部数据
Iterator<String> iter =list.iterator();
long starttime=System.currentTimeMillis();
while(iter.hasNext()) {
System.out.println(iter.next());
}
long endTime=System.currentTimeMillis();
long result=endTime-starttime;
System.out.println("LinkedList的迭代器遍历所用时间:"+result+"毫秒");
//for-get方法遍历输出list中的全部数据
starttime=System.currentTimeMillis();
for(int i=0;i<list.size();i++) {
String te=list.get(i);
}
endTime=System.currentTimeMillis();
result=endTime-starttime;
System.out.println("LinkedList的for-get遍历所用时间:"+result+"毫秒");
System.out.println("**********************************************");
ArrayList<String> list1=new ArrayList<String>();
list1.add("Java");
list1.add("真");
list1.add("有趣");
list1.add("!");
//迭代器方法遍历输出list中的全部数据
Iterator<String> iter1=list1.iterator();
long starttime1=System.currentTimeMillis();
while(iter1.hasNext()) {
System.out.println(iter1.next());
}
long endTime1=System.currentTimeMillis();
long result1=endTime1-starttime1;
System.out.println("ArrayList 的迭代器遍历所用时间:"+result1+"毫秒");
//for-get方法遍历输出list中的全部数据
starttime1=System.currentTimeMillis();
for(int i=0;i<list.size();i++) {
String te=list.get(i);
}
endTime1=System.currentTimeMillis();
result1=endTime1-starttime1;
System.out.println("ArrayList 的for-get遍历所用时间:"+result1+"毫秒");
}
}