java集合基础

List集合有三个常用的实现类
1.ArrayList: 底层部分使用数组实现,遍历熟读块。中间插入删除元素速度慢,线程不安全。
2. Vector: 底层部分同样使用数组实现,线程不安全
3.LinkedList :采用双向链表实现。元素的空间不连续。每个元素除了存放数据以外,还要存放上一个和下一个元素的地址。遍历速度慢,中间插入删除元素速度快。
List元素可以重复 Set元素不能重复 所以有的面试题会叫你去掉数组中重复的元素 可以保存进set集合,再移出来

例如
int[] x ={1,2,3,4,5,3,3,5,2,5,7,6,9,8};
//用 set下面的Hashset方法去掉重复的
Set<Integer> set = new HashSet<Integer>();
for(int i : x){
set.add(i);
}

4 Set集合常见(底层不是数组)都在util包里面
1.HashSet接口
输出的序列不一定,
例如
Set<Student> set = new HashSet<Student>();
//添加
set.add(new Student(1,"张三","男"));
遍历
因为底层不是数组,所以不能用For循环来遍历
//方法一
Iterator<Student> it = set.iterator();
while(it.hasNext()){
Student s = it.next();
System.out.println(s);
}
System.out.println("=============================");
//方法二
for(Student s:set){
System.out.println(s);
}
2,TreeSet接口
可以给集合元素排序
添加删除方法和上面一样
用 Comparator接口 来判断怎么排序 需要有重写的抽象方法 在(import java.util.Comparator;)
可以排序的set数组
Set<Student> set = new TreeSet<Student>(new Comparator<Student>() {

@Override
public int compare(Student g0, Student g1) {
return g0.getId() - g1.getId();
}
});
5,Map集合
HashMap和HashTable的区别和联系
1.HashMap和HashTable都是Map接口的实现类。一个元素可以存放两个对象。
2.HashMap允许存放空键和空值。而Hashtable不允许存放空键和空值。
3.HashMap线程不安全,而Hashtable线程安全
新建Map接口
Map<Integer,Student> map = new HashMap<Integer,Student>();

1.添加元素
map.put(1, new Student(1,"张三","男"));
2.根据键对象,查找值对象,如果没找到返回null
Student s = map.get(4);
3.根据键对象,移除元素
map.remove(2);
4.得到集合长度
System.out.println(map.size());
5.遍历方式
1. 得到Map集合的键对象
Set<Integer>keySet = map.keySet();
for(Integer x : keySet){
Student st = map.get(x);
System.out.println("键:"+x+" 值:"+st);
}

2.Collection<Student> c = map.values();
for(Student st : c){
System.out.println(st);
}

6.算法 分为 1.Arrays2. Collections 其中有个类 Collectios 不同于 Collction
1.Arrays
int[] array = new int[]{4,8,1,2,3,5,7,6,9};
1.对数组排序1
Arrays.sort(array);

for(int i : array){
System.out.println(i);
}
2.对数组排序2
Arrays.sort(array,new Comparator<Student>() {

@Override
public int compare(Student arg0, Student arg1) {
// TODO Auto-generated method stub
return arg0.getId() - arg1.getId();
}
});
2. Collections
List<Student> list = new ArrayList<Student>();

// 集合元素的添加
//写进去什么顺序 出来就是什么顺序
list.add(new Student(11, "张三", 99));
list.add(new Student(8, "李四", 89));
list.add(new Student(7, "王二", 90));
list.add(new Student(9, "飞升之后", 99));

//反转排序
Collections.reverse(list);

//乱序。随机排列元素
Collections.shuffle(list);


//排序,需要实现Comparator比较器接口,指明排序规则
Collections.sort(list,new Comparator<Student>() {

@Override
public int compare(Student arg0, Student arg1) {
// TODO Auto-generated method stub
return arg0.getGrade() - arg1.getGrade();
}
});

for(Student s : list){
System.out.println(s);
}

猜你喜欢

转载自www.cnblogs.com/jiangximing/p/8907151.html