Collection集合体系

Collection集合体系介绍

Collection集合图:

  

List集合:

   有序集合,参考ArrayList与LinkedList比较一文,

Set集合:

   无序集合,没有下标概念,不通过下标访问。

HashSet:

  HashSet中的元素不能重复,判断的依据是先比较对象的hashCode值是否相等,如果相等再比较对象的地址。

可以在类中重写hashCode和equals方法重新定义比较规则:

	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + age;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}
	
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Student other = (Student) obj;
		if (age != other.age)
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}
}

TreeSet

  特点:可以对集合中的元素进行自然排序,如果要指定排序规则,可以继承Comparable接口,或者在创建TreeSet时候,指定一个Comparable接口的实现类对象

 1 package set;
 2 
 3 import java.util.Comparator;
 4 import java.util.Set;
 5 import java.util.TreeSet;
 6 
 7 public class TestTreeSet {
 8     public static void main(String[] args) {
28         Set<Person> pSet2 = new TreeSet<Person>(new Comparator<Person>() {
29             public int compare(Person o2, Person o1) {
30                 int result = (o1.name+"").compareTo(o2.name+"");
31                 if ( result == 0 ) { // 表示两个字符串相等
32                     return o2.age - o1.age;
33                 }
34                 return result;
35             }
36         });
37         pSet2.add(new Person("张三", 20)); // zhangsan
38         pSet2.add(new Person("李四", 30)); // lisi
39         pSet2.add(new Person("李四", 25)); // lisi
40         pSet2.add(new Person("李聪", 30)); // licong
41         pSet2.add(new Person("周瑞发", 30)); // zhourunfa
42         for (Person person : pSet2) {
43             System.out.println(person);
44         }
45     }
46 }
47 
48 class Person /*implements Comparable<Person>*/{
49     String name;
50     int age;
51     
52     public Person(String name, int age) {
53         super();
54         this.name = name;
55         this.age = age;
56     }
57     
58     /*public int compareTo(Person o) {
59         // 字符串对象实现了compareTo方法,按照自然排序规则排序
60         int result = (o.name+"").compareTo(this.name+"");
61         if ( result == 0 ) { // 表示两个字符串相等
62             return this.age - o.age;
63         }
64         return result;
65     }*/
66 
67     public String toString() {
68         return "Person [name=" + name + ", age=" + age + "]";
69     }
70 }

LinkedHashSet:

  特点:有序、不可重复的容器

  

Map集合体系:

  

不重要,自行百度

猜你喜欢

转载自www.cnblogs.com/aqiu-jiang/p/11201563.html