初识java集合2

来源:互联网 发布:全球购海淘宝 编辑:程序博客网 时间:2024/06/07 05:32

set集合分析

 

不允许包含重复元素,Set判断俩个对象相同使用的是equals方法,当俩个对象用equals方法比较返回true时,则不接受这俩个对象,否则,接受。

只有当需要一个保持排序的set时,才应该使用TreeSet,否则都用HashSetEnumSet只能保存同一个枚举类的枚举值作为集合元素,三者都是线程不安全的。

 

HashSet

特点:

       1.不能保证元素的排列顺序,顺序可能改变。

        2.HashSet不同步,当多线程修改其集合时,必须保证代码同步。

        3.集合元素值可以为NULL

 

HashSet集合判断两个元素相等的标准是  两个对象通过equals方法比较相等,并且两个对象的hashCode()方法返回值也相等。

当程序向HashSet集合中添加元素时,HashSet会根据集合的hashCode来计算其存储位置。也就是每个元素的hashCode值就可以决定其索引,HashSet采用每个元素的hashCode值来计算其索引,所以可以自由增加hashCode的值,并根据其值来访问元素

 

LinkedHashSetHashSet的子类,使用链表维护元素的次序,当遍历其集合元素时,LinkedHashSet会按照元素的添加顺序来访问集合的元素。

public class Demo

{

public static void main(String args)

{

Demo students= new Demo();

students.add("王二");

students.add("张三");

System.out.println(students);//输出结果王二张三

books.remove("王二");

books.add("王二");

System.out.println(books);//输出结果张三王二元素的顺序与添加顺序一致
}
}

 

TreeSet

TreeSet类不是根据元素的插入顺序排序的,而是根据元素的实际值大小排序的

TreeSet的两种排序

自然排序:

//TreeSet添加元素时,只有第一个元素不需要实现Comparable接口,后面添加的所有元素必须实现Comparable接口

class Z implements Comparable

{

int age;

public Z(int age)

{

this.age=age;
}

//重写equals方法

public boolean equals(Object obj)

{

return true;
}

//重写compareto方法,总是返回正整数

public int compareTo(Object obj)

{

return 1;
}

}

public class TreeSetTest2

{

public static void main(String[] args)

{

TreeSet set =new TreeSet();

Z zl =new Z(6);

set.add(zl);

System.out.println(set.add(z1));//把同一个对象再次添加到TreeSet集合中,compare to方法返回一,equals方法返回true,所以TreeSet认为Z1对象和它自己的对象也不相等

System.out.println(set);

((Z)(set.first())).age=9;//同一个元素,

System..out.println(((Z)(set.last())).age);
}
}

 

定制排序

class M

{

int age;

public  M(int age)

{

this.age=age;
}

public String toString()

{

return "M[age:"+age+"]";
}
}

public class TreeSetTest4

{

public static void main(String[] args)

{

TreeSet  ts = new TreeSet(new Comparator()

{

public int compare(Object o1,Object o2)

{

M m=(M) o1;

M m2=(M) o2;

return m1.age>m2.age? -1

: m1.age<m2.age? 1:0;
}

});

ts.add(new M(5));

ts.add(new M(-3));

ts.add(new M(9));

System.out.println(ts);
}

}

 

EnumSet

其所有元素都必须指定枚举类型的枚举值

EnumSet集合不允许加入null元素

enum Season

{

SPRING,SUMMER,FALL,WINNER
}

public class EnumSetTest

{

public static void main(String[] args)

{

//创建一个EnumSet集合,集合元素就是Season枚举类的全部枚举值

EnumSet es1 =EnumSet.allOf(Season.class);

System.out.println(es1);

Enumset es2=EnumSet.noneof(Season.class);

//手动添加两个元素

es2.add(Season.WINTER);

es2.add(Season.SPRING);

System.out.println(es2);

EnumSet es3=EnumSet.of(Season.SUMMER,Season.WINTER);

System.out.println(es3);

EnumSet es4=EnumSet.ranage(Season.SUMMER,Season.WINTER);

System.out.println(es4);

EnumSet es5=EnumSet.co,plementOf(es4);

System.out.println(es5);


}
}

0 0
原创粉丝点击