The root interface in the <i>collection hierarchy</i>. A collection* represents a group of objects, known as its <i>elements</i>. Some* collections allow duplicate elements and others do not. Some are ordered* and others unordered. The JDK does not provide any <i>direct</i>* implementations of this interface: it provides implementations of more* specific subinterfaces like {@code Set} and {@code List}. This interface* is typically used to pass collections around and manipulate them where* maximum generality is desired.
简单来说就是用于储存元素的集合
提供获取,移除,遍历,判断是否存在等功能
List接口
继承于Collection接口
其上的javadoc描述
An ordered collection (also known as a <i>sequence</i>). The user of this
interface has precise control over where in the list each element is
inserted. The user can access elements by their integer index (position in
the list), and search for elements in the list.<p>
简单来说就是一个有序集合
其最常用的实现类为ArrayList和LinkedList
以ArrayList为例
其中我们引入了一个新符号<>,这个指示其中应该存入什么类型的数据,被称为泛型,后面再讲
List<Integer> list =newArrayList<>();list.add(1000);System.out.println(list.get(0));
这个就是向第一个位置插入1000这个值,再获取
ArrayList你可以简单理解为可以自动伸缩的”数组“
ArrayList和LinkedList对比
实现原理
是否支持随机读取
是否支持自动扩展
ArrayList
数组
是
是(数组扩容)
LinkedList
双向链表
否
是(链表天然支持)
Set接口
继承于Collection接口
其上javadoc描述
A collection that contains no duplicate elements. More formally, sets
contain no pair of elements {@code e1} and {@code e2} such that
{@code e1.equals(e2)}, and at most one null element. As implied by
its name, this interface models the mathematical <i>set</i> abstraction.
简单来说就是无论如何插入都会保证无重复数据
常用实现类为HashSet
HashSet<Integer> set =newHashSet<>();set.add(100);set.add(100);set.add(2);System.out.println(set.size());
publicstaticvoidmain(String[] args) throws Throwable {ArrayList<String> list =newArrayList<>();addElement(list);String s =list.get(0); }publicstaticvoidaddElement(List strings){strings.add(100); }
报错信息
Exception in thread "main" java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.String (java.lang.Integer and java.lang.String are in module java.base of loader 'bootstrap')
at com.Main.main(Main.java:19)