笔记内容总结于:为什么要使用集合?_哔哩哔哩_bilibili
目录
1.为什么要使用集合
集合的主要作用:存储数据
Java中存储数据的方法,如(1)变量的形式进行存储,(2)用数组来存储
但为什么需要使用集合进行数据存储?
案例:假如要统计学校某个班所有同学的成绩,你需要怎么存储这些成绩?
方法1:变量的形式存储
int score1=90;
int score2=85;
int score3=88;
int score4=92;
int score5=81;
int score6=83;
可以存储,但数据少的话可以存储,但数据量多的时候,代码编写会繁琐,程序不美观,也不便于计算
方法2:用数组存储
int [] score = new int[5];
score[0]=80;
score[1]=83;
score[2]=85;
score[3]=90;
score[4]=81;
score[5]=82;
首先数组有个致命的特点:创建时需指定其长度,并且在使用时长度不可改变,而我们是数据后续还需要增加,我们需要找一个可变长度的容器来存储数据,所以使用数组也不合适
因此Java提供了集合,它里面有各种各样存储数据的容器
并且每个容器的长度都是可变的,我们只管往里面存,空间如果不够,它自己会调
Collection<Integer> scores = new ArrayList<>();
scores.add(80);
scores.add(82);
scores.add(85);
scores.add(90);
scores.add(81);
scores.add(83);
如上代码,集合不用像数组一样,按照下表存储,直接调用add方法,就可以把数据存储上去
集合中还有很多像add一样的方法
public interface Collection<E> extends Iterable<E> {
//add增加数据
boolean add(E e);
//remove删除集合中某个数据
boolean remove(Object 0);
//size集合中有多少条数据
int size();
//判断集合是否为空
boolean isEmpty();
.....
}
集合框架中的另一个体系:Map,key-value键值对体系
总结:什么时候需要用集合?
1.存储数据量大
2.存储数据需要添加或减少,而集合中的容器能可变长度
2.集合中的方法
Collection中的17个抽象方法
public interface Collection<E> extends Iterable<E>{
//01.修改操作
//添加数据
boolean add(E e);
//删除数据
boolean remove(Object o);
//02.查询操作
//查询集合中有多少数据
int size();
//集合是否为空
boolean isEmpty();
//集合中是否包含某个数据
boolean contains(Object 0);
Iterator<E> iterator();
Object[] toArray();
<T> T[] toArray(T[] a);
//批量操作
boolean containsAll(Collection<?> c);
//添加批量数据
boolean addAll(Collection<? extends E> c);
//删除批量数据
boolean removeAll(Collection<?> c);
default boolean removeIf(Predicate<? super E> filter)
boolean retainAll(Collection<?> c);
//清空集合
void clear();
Spliterator<E> spliterator();
Stream<E> stream();
Stream<E> parallelStream();
}