1、Collection集合常用语法
boolean add(E e) 添加元素
boolean remove (OBject o) 删除指定元素
void clear() 清空集合中的元素
boolean contains(Object o)判断集合中是否存在指定元素
boolean isEmpty() 判空
int size() 长度
2、Collection的遍历
iterator迭代器 和c++一样
iteratoriterator() 返回集合元素的迭代器,通过集合的iterator()方法得到。
next() 返回迭代的下一个元素
hasNext() 如果迭代具有更多的元素 则返回true
3、List
1.特点:有序、允许重复
2、特有特点
void add(int index,E e) 在集合指定位置插入指定元素
E remove(int index) 删除指定索引处的元素 返回被删除的元素
E set(int index,E e) 修改指定索引处的元素,返回被修改的元素
E get(int index) 返回指定索引处的元素
3、List 的for循环遍历
for(int i=0;i<list.size( );i++){
ElementType e=list.get(i );
}
4、并发修改异常 用for循环获取元素
5、ListIterator 列表迭代器(解决并发修改异常)
1.特有的方法:
boolean hasPrevious( ) 此列表迭代器反向遍历列表具有更多的元素,返回true 与hasnext()相反
E previous( )返回列表上一个元素; 与next()相反
add(E e); 将指定元素插入列表
6、增强for循环(底层是迭代器)
for(string i: list){
cout<<i<<endl;
}
7、数据结构
8、LinkedList(链表)
addFirst(E e) 在该列表开头插入指定元素
addLast(E e) 将指定元素追加到此列表 末尾
E getFirst() 返回列表的第一个元素
E getLast() 返回列表的最后一个元素
E removeFirst( ) 从链表中删除返回第一个元素
E removeLast( ) 从列表删除返回最后一个元素
9.ArrayList 的对象排序
运用比较器排序comparator
Student t1 = new Student(12, "知识");
Student t2 = new Student(13, "awdwa");
Student t3 = new Student(11, "1adad");
Student t4 = new Student(11, "awdwa");
Student t5 = new Student(14, "sdaad");
ArrayList<Student> array=new ArrayList<Student>();
array.add(t1);
array.add(t2);
array.add(t3);
array.add(t4);
array.add(t5);
//借助Collections的sort方法
//Collections.sort(List<T>list);
//Collections.sort(List<T>list,new Comparator <O o>)()}
Collections.sort(array, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
int num=o1.getAge()-o2.getAge();
int num1=num==0?o1.getName().compareTo(o2.getName()):num;
return num1;
}
});
for(Student s:array){
System.out.println(s.getAge()+"这是一个分隔符"+s.getName());
}
4.Set集合(方法和collection一致)
1.特点:无重复,无索引
2.哈希值(jdk根据对象的地址或字符串 数字算出来的int的数值)
int hashcode() Object类就有
同一个对象多次调用 hashCode()方法返回的哈希值是相同的
通过方法重写,可以实现不同对象哈希值的重写
3.HashSet集合概述和特点
1.底层数据结构是哈希表
2.对集合的迭代顺序不作任何保证
3、没有带索引的方法,所以不能使用普通的for循环遍历
4.无重复
4.LinkedHashSet集合概述和特点
1.哈希表和链表实现的set接口,具有可预测的迭代次序
2.有链表保证元素有序,也就是说元素的存储和取出顺序是一致的
3.由哈希表保证元素唯一,
5.TreeSet
1.元素有序,这里的顺序不是指存储和取出的顺序,而是按照一定的规则进行排序,具体的排序方式取决于构造方法
TreeSet():根据其元素的自然排序进行排序
TreeSet(Comparator com):根据指定的比较器进行排序
关于Comparable的使用
在类里重写compareTo(To)方法,重写方法时,一定要注意排序规则所要求的主要条件和次要条件
6.比较器排序Comparator的使用
重写compare(T o1,T o2)的方法,重写方法时,一定要注意排序规则所要求的主要条件和次要条件
TreeSet<Student> ts=new TreeSet<Student>(new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return 0;
}
});