------- <a href="http://www.itheima.com" target="blank">android培训</a>、<a href="http://www.itheima.com" target="blank">java培训</a>、期待与您交流! ----------
一、List接口:有序的collection,可以重复,允许null元素。
1、ArrayList
1)、默认数组大小为10
2)、动态扩充数组,算法:(原数组长度*3/2)+1
3)、内部使用动态数组实现
4)、如果已知元素个数,可以指定初始容量的构造ArrayList对象,这样可以提高效率。5)、使用插入或删除会导致数组移位。影响性能。
6)、线程不安全
add(位置,o)
remove(位置,o)
get(位置)
contain(o)
clear()
index(o)首次出现的位置
isEmpty()
比较重要的代码(动态扩充)
//添加
public void add(Person p){
if(count>=Person.length){
int newLen=(Person.length*3)/2+1;
Person=Arrays.copyOf(Person, newLen);
}
Person[count]=p;
count++;
}
2、Vector
1)、默认数组大小为10
2)、动态扩充数组,算法:容器+增量:没增量则容量*2
3)、线程安全
3、LinkedList1)、双向链表实现
2)、适合插入,删除操作很方便。
二、set接口:不包含重复元素。最多包含一个null元素。
1、HashSet
1)、不保证迭代顺序,顺序会变。
2)、默认数组大小为16,加载因子是0.75(75%满了就扩充)
3)、底层使用HashMap实现(哈希表)
4)、对象会重复(e1.equals(e1))重写equals()和hashCode()方法,可避免重复。
迭代器iterator()
1)、使用元素的自然顺序对对象元素进行排序。
2)、在TreeSet集合中存储自定义对象时,该对象必须实现Comparator()
比较重要的代码(按照年龄排序)
public class Person implements Comparable<Person>{
private String name;
private int age;
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public Person() {
super();
// TODO Auto-generated constructor stub
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) 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;
}
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;
}
@Override
public int compareTo(Person o) {
if(o.getAge()==0){
try {
throw new Exception("error");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(this.age<o.getAge()){
return -1;
}else if(this.age>o.getAge()){
return 1;
}
return 0;
}
}
注意点:Collection<E>接口和Collections不同(不知道的http://pengcqu.iteye.com/blog/492196)
java.util.Collection 是一个集合接口。
java.util.Collections 是一个包装类。它包含有各种有关集合操作的静态多态方法。此类不能实例化,就像一个工具类,服务于Java的Collection框架。
黄线没定义泛型
集合转换数组toArray(T[] a)