📄 collectiontest.java
字号:
//演示集合类的用法
import java.util.*;
class CollectionTest
{
public static void printElements(Collection c)
{
System.out.println("Elements in collection as follows:");
Iterator it = c.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
}
public static void main(String[] args)
{
/*
ArrayList al = new ArrayList();
al.add(new Point(1, 1));
al.add(new Point(2, 2));
al.add(new Point(3, 3));
//for (int i=0; i<al.size(); i++)
//{
System.out.println(al);
//}
Object[] objs = al.toArray();
for (int i=0; i<objs.length; i++)
{
System.out.println(objs[i]);
}
List l = Arrays.asList(objs); //返回一个固定的列表
System.out.println(l);
printElements(al);
//迭代器用法
/*
Iterator it = al.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
*/
ArrayList al = new ArrayList();
Student s1 = new Student(2, "zhangshan");
Student s2 = new Student(1, "lisi");
Student s3 = new Student(3, "wangwu");
Student s4 = new Student(2, "mybole");
al.add(s1);
al.add(s2);
al.add(s3);
al.add(s4);
//Collections.sort(al, new Student.StudentCmp());
Collections.sort(al, Collections.reverseOrder());
printElements(al);
}
}
class Point
{
int x,y;
Point(int x, int y)
{
this.x = x;
this.y = y;
}
public String toString()
{
return "x=" + x + ", y=" + y;
}
}
class Student implements Comparable
{
int num;
String name;
Student(int num, String name)
{
this.num = num;
this.name = name;
}
//使用内部类构造一个比较器(总与特定的类相关)
static class StudentCmp implements Comparator
{
public int compare(Object o1, Object o2)
{
System.out.println("Compare");
int result;
Student s1 = (Student)o1;
Student s2 = (Student)o2;
result = s1.num > s2.num ? 1 : (s1.num == s2.num ? 0 : -1);
//如果学号相等,则按名字排序
if (0 == result)
{
result = s1.name.compareTo(s2.name);
}
return result;
}
}
public int compareTo(Object o)
{
System.out.println("Compareto");
Student s = (Student)o;
return num > s.num ? 1 : (num == s.num ? 0 : -1);
}
public String toString()
{
return num + ": " + name;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -