第三章:集合01
一:集合的框架结构图
1. 集合和数组的区别:
2.Collection集合的方法:
public class CollectionTest01 {
public static void main(String[] args) {
//创建一个集合对象
//Collection c = new Collection() //接口抽象的,无法实例化
Collection c = new ArrayList();//多态
//测试Collection中的常用方法
/*
自动装箱,实际上是放进去了一个对象的内存地址,Integer x = new Integer;
*/
c.add(1200);
c.add(3.14);
c.add(new Object());
c.add(true);
/*
获取集合中元素的个数
*/
System.out.println("集合中元素的个数:" + c.size());
/*
清空集合
*/
c.clear();
System.out.println("集合中元素的个数:" + c.size());
c.add("hello");//将"hello"对象的内存地址放到集合当中。
c.add("world");
c.add("浩克");
c.add("绿巨人");
c.add(1);
/*
如果此 collection 包含指定的元素,则返回 true。
*/
System.out.println(c.contains("浩克"));
System.out.println(c.contains("浩克2"));
System.out.println(c.contains(1));
/*
从此 collection 中移除指定元素。
*/
System.out.println("集合中元素的个数:" + c.size());
c.remove(1);
System.out.println("集合中元素的个数:" + c.size());
/*
判断集合是否为空(集合中是否存在元素)。
*/
System.out.println(c.isEmpty());
c.clear();
System.out.println(c.isEmpty());
/*
将集合中的元素转换为数组
*/
c.add("abc");
c.add("def");
c.add(100);
c.add("hello world");
c.add(new Student());
Object[] obj= c.toArray();
for (int i =0; i<obj.length;i++){
System.out.println(obj[i]);
}
}
}
class Student{
}
public class CollectionTest02 {
public static void main(String[] args) {
Collection c = new ArrayList();
String s1 = new String("abc");
String s2 = new String("def");
String x = new String("abc");
c.add(s1);
c.add(s2);
System.out.println(c.contains(x));//判断集合总是否存在x
}
}
/*
存放在集合中的类型,一定要重写equals方法
*/
public class CollectionTest03 {
public static void main(String[] args) {
Collection c = new ArrayList();
User u1 = new User("jack");
User u2 = new User("jack");
c.add(u1);
//没有在User类中重写equals方法所以值为false
System.out.println(c.contains(u2));
}
}
class User{
private String name;
public User(){}
public User(String name){
this.name = name;
}
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// User user = (User) o;
// return user.name.equals(this.name);
// }
}
3. 常用集合的分类:
Collection 接口的接口 对象的集合(单列集合)
├——-List 接口:元素按进入先后有序保存,可重复
│—————-├ LinkedList 接口实现类, 链表, 插入删除, 没有同步, 线程不安全
│—————-├ ArrayList 接口实现类, 数组, 随机访问, 没有同步, 线程不安全
│—————-└ Vector 接口实现类 数组, 同步, 线程安全
│ ———————-└ Stack 是Vector类的实现类
└——-Set 接口: 仅接收一次,不可重复,并做内部排序
├—————-└HashSet 使用hash表(数组)存储元素
│————————└ LinkedHashSet 链表维护元素的插入次序
└ —————-TreeSet 底层实现为二叉树,元素排好序
Map 接口 键值对的集合 (双列集合)
├———Hashtable 接口实现类, 同步, 线程安全
├———HashMap 接口实现类 ,没有同步, 线程不安全-
│—————–├ LinkedHashMap 双向链表和哈希表实现
│—————–└ WeakHashMap
├ ——–TreeMap 红黑树对所有的key进行排序
└———IdentifyHashMap