集合

 List集合有三个常用的实现类:
ArrayList:底层部分使用数组实现,遍历速度快,中间插入和删除元素速度慢,线程不安全;
vector:底层部分同样使用数组实现,线程安全的类;
LinkedList:采用双项链表实现,每个元素除了存放数据以外,还要存放上一个和下一个元素的地址,遍历速度慢,中间插入删除元素速度快;


[Set][HashSet]

set集合里面的元素不能重复,加进去元素位置和取元素出来的位置不同
例:
Set<Student> stuSet = new HashSet<Student>();
//添加元素
stuSet.add(new Student(1,"张三",80));
stuSet.add(new Student(2, "李四", 20));
stuSet.add(new Student(3, "王五", 50));
stuSet.add(new Student(4, "赵六", 60));
        
//遍历方式
//①迭代器
Iterator<Student> it = stuSet.iterator();
while (it.hasNext()) {
    System.out.println(it.next());
}
//②
for (Student student : stuSet) {
    System.out.println(student);
}

[Set][TreeSet]

对元素进行排序;
例:
用比较器来排序成绩    --详见API
Set<Student> stuSet = new TreeSet<Student>(new Comparator<Student>() {

    @Override 
    public int compare(Student o1, Student o2) {
            //升序  
            return o1.getScore() - o2.getScore();
    }
});
//添加元素
stuSet.add(new Student(1,"张三",80));
stuSet.add(new Student(2, "李四", 20));
stuSet.add(new Student(3, "王五", 50));
stuSet.add(new Student(4, "赵六", 60));


[Map][hashMap]

Map<Integer, Student> map = new HashMap<Integer, Student>();
//添加元素
map.put(1, new Student(1,"张三",80));
map.put(2, new Student(2, "李四", 20));
map.put(3, new Student(3, "王五", 50));
map.put(4, new Student(4, "赵六", 60));
        
//根据键,得到值,没有找到返回null
Student stu = map.get(2);
System.out.println(stu);
//得到集合长度
System.out.println(map.size());

//遍历
//第一种:得到map集合的键集合
Set<Integer> keySet = map.keySet();
for (Integer key : keySet) {
    Student s = map.get(key);
    System.out.println("键 "+key+"   值 "+s);
}


//第二种:得到map集合的值集合
Collection<Student> col = map.values();
for (Student student : col) {
    System.out.println(student);
}

hashMap 和 hashTable的区别和联系:
1. hashMap和hashTable都是Map的接口的实现类,一个元素可以存放两个对象。
2. hashMap允许存放空键和空值,而hashTable不允许存放空键和空值。
3. hashMap线程不安全,而hashTable线程安全。

int[] array = new int[] {4,6,7,32,5,3,2,1};
//对数组进行排序

Arrays.sort(array);
        
for (int i : array) {
    System.out.println(i);
}
        
Student[] stuArray = new Student[2];
stuArray[0] = new Student(1, "张三", 80);
stuArray[1] = new Student(2, "李四", 20);
        
Arrays.sort(stuArray, new Comparator<Student>() {

    @Override
    public int compare(Student o1, Student o2) {
        return o1.getScore() - o2.getScore();
    }
});
        
for (Student s : stuArray) {
    System.out.println(s);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值