作业1:
使用ArrayList集合,对其添加100个不同的元素:
1.使用add()方法将元素添加到ArrayList集合对象中;
2.调用集合的iterator()方法获得Iterator对象,并调用Iterator的hasNext()和next()方法,迭代的读取集合中的每个元素;
3.调用get()方法先后读取索引位置为50和102的元素,要求使用try-catch结构处理下标越界异常
package week13;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.management.RuntimeErrorException;
public class ConnectionDemo01 {
public static void main(String[] args) {
// TODO Auto-generated method stub
List<Integer> arrayList = new ArrayList<Integer>();
for(int i = 0; i < 100 ; i++){
arrayList.add(new Integer((int) (Math.random() * 1000)));
}
System.out.println("迭代器输出结果:");
Iterator<Integer> iterator = arrayList.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next().intValue());
}
try {
System.out.print("调用get()读取索引位置为50的元素:");
System.out.println(arrayList.get(50));
System.out.print("调用get()读取索引位置为102的元素:");
System.out.println(arrayList.get(102));
} catch (IndexOutOfBoundsException e) {
// TODO Auto-generated catch block
System.out.println("数组越界了");
e.printStackTrace();
}
}
}
运行截图:
作业2:
选择某种Map集合保存学号从1到15的学员的学号(键)和姓名(值),学号用字符串表示,输入的时候要以学号乱序的方式存入Map集合,然后按照学号从大到小的顺序将Map集合中的元素输出打印。需要自定义Map集合的比较器Comparator,因字符串对象的大小比较是按字典序,而非对应的数值。
要求:必须使用Map集合的内部排序机制进行排序,不能在外部排序。
package week13;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.TreeMap;
public class MapSort{
public static void main(String[] args) {
List<Student> list = new ArrayList<Student>();//用来乱序输出的
for (int i = 1; i < 16; i++) {
list.add(new Student(String.valueOf(i), "tjw_"+i));
}
TreeMapMethod(list);
}
private static void TreeMapMethod(List<Student> list) {
//treeMap按key来从大到小排序
TreeMap<String, Student> map = new TreeMap<String, Student>(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
int sno1 = Integer.valueOf(o1).intValue();
int sno2 = Integer.valueOf(o2).intValue();
return sno2 - sno1;
}
});
int listSize = list.size();
Student student;//用作接收,省去下边一直new
System.out.println("乱序输入的顺序:");
while (listSize != 0) {
int temp = (int) (Math.random() * listSize);
System.out.println(list.get(temp));//这里打开注释可以查看乱序存入的顺序
student = list.get(temp);
map.put(student.Sno, student);
list.remove(temp);
listSize -= 1;
}
Collection<Student> studentsCollection = map.values();
Iterator<Student> iterator = studentsCollection.iterator();
System.out.println("排好序的输出结果:");
while (iterator.hasNext()) {
student = iterator.next();
System.out.println("学号:"+student.Sno+" "+"姓名:"+student.name);
}
}
}
class Student{
String Sno;
String name;
public Student(String sno, String name) {
super();
Sno = sno;
this.name = name;
}
@Override
public String toString() {
return "Student [Sno=" + Sno + ", name=" + name + "]";
}
}
运行截图:
总结:还有种麻烦点的思路,hashMap转成ArrayList,然后Collections.sort(List,Comparator),至于乱序方式存入,写完之后翻了翻书才发现Collections类有个public static void shuffle(List list)的方法,也就是对list中的数据按洗牌算法重新随机排列,经过这一步之后直接一个for循环挨个存入Map就行了,也不用动脑子直接调方法就行了