讲到List 集合 就要说到 数组。
数组和集合的区别?
相同点:
不同点:
数组长度不可变,集合长度可以变
数组只能存储 基本类型,集合可以存储任意类型
List 接口的特点
Collection 接口 中 的 remove方法 接收的是 元素,List 集合中的 remove 方法接收的是索引
常见的 List 集合
ArrayList、LinkedList
特点
ArrayList 底层是 数组 ,在数据结构中 数组 是查询快,增删慢
LinkedList 底层是 链表,在数据结构中 链表 是查询慢,增删快

Collection 接口多态 ArrayList 操作的对象
@Testpublic void testArrayList(){Collection collection = new ArrayList<String>();// 添加元素collection.add("张1");
collection.add("张2");
collection.add("张3");
collection.add("张4");
collection.add("张1"); // ArrayList 值相同 不会覆盖System.out.println(collection.size()); // 5collection.remove("张4");
System.out.println(collection.size()); // 4boolean flag = collection.contains("张1");
System.out.println(flag); // trueboolean empty = collection.isEmpty();
System.out.println(empty); // flasecollection.clear();
System.out.println(collection.size()); // 0}
ArrayList 的操作
@Testpublic void ListForArrayList(){
List<String> list = new ArrayList<>();// 往 ArrayLisr 集合中 添加元素list.add("张1");
list.add("张2");
list.add("张3");
list.add("张4");
list.add("张1"); // ArrayList 值相同 不会覆盖list.forEach(a -> System.out.print(a+",")); // 张1,张2,张3,张4,张1,// 替换元素 数组 从0 开始 替换 索引下标为1 的 元素 即 0 1 是第二个元素 故 张2 被替换list.set(1,"我被替换了");
System.out.println();
list.forEach(a -> System.out.print(a+",")); // 张1,我被替换了,张3,张4,张1,System.out.println();// 获取 第索引下标为 2 的元素String s = list.get(2);
System.out.println(s); // 张3// 删除 索引下标为 3 的元素list.remove(3); // 李4 被删除list.forEach(a -> System.out.print(a+",")); // 张1,我被替换了,张3,张1,}
面试题
集合中只要重写了equals()必须重写hashCode()
set存储是不重复对象,依据hashCode()和equals()进行判断
如果自定义对象作为Map的键,必须重写hashMap()和equals(),我们常用的HashMap<String,Object> 可以直接使用的原因是:String这个类就重写hashMap()和equals()!
还没有评论,来说两句吧...