一,测试ArrayList,KinkedList的get方法的性能差别。
二,使用ArrayList,LinkedList集合存储学生对象。
分别用年龄,身份证号对所有学生对象排序。
排序时分别使用List.sort方法和Collections.sort方法排序
第二题
package test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
public class Student {
private String name;
private int age;
private String idNum;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getIdNum() {
return idNum;
}
public void setIdNum(String idNum) {
this.idNum = idNum;
}
public Student(String name, int age, String idNum) {
this.name = name;
this.age = age;
this.idNum = idNum;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + ", idNum=" + idNum + "]";
}
public static void main(String[] args) {
Student s1 = new Student("张三", 12, "8498491511");
Student s2 = new Student("张三2", 55, "8498491511");
Student s3 = new Student("张三3", 13, "8498491511");
Student s4 = new Student("张三", 60, "8498491511");
Student s5 = new Student("张三4", 88, "8498491511");
Student s6 = new Student("张三5", 23, "8498491511");
Student s7 = new Student("张三6", 26, "8498491511");
Student s8 = new Student("张三7", 36, "8498491511");
List<Student> l1 = new ArrayList<>();
l1.add(s1);
l1.add(s2);
l1.add(s3);
l1.add(s4);
l1.add(s5);
l1.add(s6);
l1.add(s7);
l1.add(s8);
List<Student> l2 = new LinkedList<>();
l2.add(s1);
l2.add(s2);
l2.add(s3);
l2.add(s4);
l2.add(s5);
l2.add(s6);
l2.add(s7);
l2.add(s8);
// 按照年龄排序
l1.sort(Comparator.comparing(Student::getAge));
l1.forEach(System.out::println);
System.out.println();
// 按身份证号
l1.sort(Comparator.comparing(Student::getIdNum));
l1.forEach(System.out::println);
System.out.println();
// 按照年龄排序
Collections.sort(l2, Comparator.comparing(Student::getAge));
l2.forEach(System.out::println);
System.out.println();
// 按身份证号
Collections.sort(l2, Comparator.comparing(Student::getIdNum));
l2.forEach(System.out::println);
System.out.println();
}
}
第一题
public class TestList {
public static void main(String[] args) {
Random random = new Random();
IntStream intStream1 = random.ints(0, 100000);
// 产生9999个0-100000的随机数
List<Integer> l1 = intStream1.limit(9999).boxed().collect(Collectors.toList());
IntStream intStream2 = random.ints(0, 100000);
// 产生9999个0-100000的随机数
LinkedList<Integer> l2 = intStream2.limit(9999).boxed().collect(Collectors.toCollection(LinkedList::new));
// 结果差异还是挺大的
test(l1);
test(l2);
}
private static <T> void test(List<T> list) {
long startTime = System.nanoTime();
for (int i = 0; i < list.size(); i++) {
list.get(i);
}
long endTime = System.nanoTime();
// 转为毫秒
double time = (endTime - startTime) / 1000000;
System.out.println("取出" + list.size() + "个元素,共花费:" + time);
}
}