集合Collection(接口):
List(接口):
ArrayList:底层是数组,是非线程安全的
查找块,增删慢
LinkedList:底层是链表是非线程安全的
查找慢,增删块
Vector:底层是数组,是线程安全的
查找块增删慢
set(接口)元素是唯一的:
hashSet底层是哈希表:通过使用hashcode和equals方法实现唯一性(如果存储的是类对象只需要重写这两个方法就可以)
TreeSet:底层是红黑树:已经拍好序了,
自然排序:
是默认的排序
机器排序:
如果我们存储类对象,那么这个类要继承Comparable方法,或者在创建TreeSet的对象的时候使用匿名对象的方式
如:方式1
Class Student implements Comparable<Student>{
private String name;
private String age;
public Student(){
super();
}
public Student(String name,int age){
super();
this.name = name;
this.age = age;
}
public void setName(String name){
this.name = name;
}
public void setAge(int age){
this.age= age;
}
public String getName(){
return name;
}
public int getAge(){
return age;
}
public int compareTo(Student s){
int num1 = this.age - s.age;
int num2 num1 == 0?s.name.compareTo(s.getName)"num1;
return num2;
}
}
public Class Demo{
public static void main(String[] args){
TreeSet<Student> treeset = new TreeSet<Student>()
Student s = new Student("jack",23);
treeset.add(s);
}
}
方式2:
Class Student1{
private String name;
private int age;
public Student1(){
super();
}
public Student1(String name,int age){
super();
this.name = name;
this.age = age;
}
public void setName(String name){
this.name = name;
}
public void setAge(int age){
this.age =age;
}
public String getName(){
return this.name;
}
public int getAge(){
return age;
}
}
public Class Demo1{
public static void main(String[] args){
TreeSet treeset = new TreeSet(new Comparator{
public int compare(Student1 s1,Student1 s2){
int num1 = s1.getAge - s2.getAge;
int num2 = num1== 0?s1.getName.compareTo(s2.getName):num1;
return num2;
}
});
Student1 s =new Student("tom",24);
treeset.add(s)
}
}
方式3:
Class Student2{
private String name;
private int age;
public Student2(){
super();
}
public Student2(String name,int age){
super();
this.name = name;
this.age = age;
}
public void setName(String name){
this.name = name;
}
public void setAge(int age){
this.age = age;
}
public String getName(){
return name;
}
public int getAge(){
return age;
}
}
Class MyComparable implements Comparable<Sudent2>{
public int compare(Student2 s1,Student2 s2){
int num1 = s1.getAge - s2.getAge;
int num2 = num1==0?s1.getName.compareTo(s2.getName):num1:
return num2;
}
}
public Class Demo2{
public static void main(String[] args){
TreeSet<Student2> treeset = new TreeSet<Student2>(new MyComparable());
Student2 s = new Student2("smith",25);
treeset.add(s);
}
}
map(接口):
是由键值对组成的,键唯一,值可以不唯一:
hashMap:和上面的hashSet一样
TreeMap:和上面的TreeSet一样
Collection和Map
最新推荐文章于 2024-05-28 16:30:17 发布