//Collection
package sunday;
import java.util.*;
public class Demo {
public static void main(String[] args) {
// 创建集合、List
Collection<Tools> c=new LinkedList<>();
List<Tools> list=new LinkedList<>();
ArrayList<Tools> array=new ArrayList<>();
LinkedList<Tools> link =new LinkedList<>();
// 创建学生对象
Tools t1=new Tools(1,"罗宾");
Tools t2=new Tools(2,"汉库克");
Tools t3=new Tools(3,"佩罗娜");
// 添加对象
c.add(t1);
c.add(t2);
c.add(t3);
list.add(t1);
list.add(t2);
link.addFirst(t3);
// Tools tt=link.get(0);
// System.out.println(tt.getAge())
// 迭代遍历
Iterator<Tools> i=c.iterator();
while (i.hasNext()){
Tools t=i.next();
System.out.println(t.getAge());
}
// for循环
for(int i1=0;i1<list.size();i1++){
Tools t=list.get(i1);
System.out.println(t.getAge());
}
// 增强for循环
for(Tools t:list){
System.out.println(t.getAge());
}
// 创建集合对象,set
// HashSet<Tools> hs=new HashSet<Tools>();//随机存储
// LinkedHashSet<Tools> lh=new LinkedHashSet<Tools>();
TreeSet<Tools> ts=new TreeSet<Tools>(new Comparator<Tools>() {
// @Override,匿名类,比较器排序
public int compare(Tools o1, Tools o2) {
int num=o2.getAge()-o1.getAge();
// int num2=num==0?o1.getName().compareTo(o2.getName()):num;
return num;
}
});
Tools t4=new Tools(1,"罗宾");
ts.add(t1);
ts.add(t2);
ts.add(t4);
// stronger for
for(Tools t:ts){
System.out.println(t.getName()+t.getAge());
}
}
}
//c.remove(t1);移除对象
//c.clear();清空集合
//c.contains(t1);判断集合是否存在指定元素
//c.isEmpty();判断集合是否为空
//c.size();集合元素的个数
// list.add(0,t2);
//t1.hashcode();对象的哈希值
package sunday;
public class Tools implements Comparable<Tools> {
private int age;
String name;
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 Tools(int age, String name) {
this.age = age;
this.name = name;
}
@Override
// 自然排序
public int compareTo(Tools o) {
int num=o.age-this.age;
return 0;
}
}