luohzzz

导航

ArrayList集合接口

ArrayList集合接口的实现
特点是:有序、有下标、可以重复
1、add、remove、clear
2、迭代器Iterator的遍历、迭代器ListIterator的遍历
3、contains判断是否存在、isEmpty判断是否为空、indexOf获取某个元素的位置

 

```java
ArrayList arrayList = new ArrayList();

Student s1 = new Student("xiaoming",21);
Student s2 = new Student("xiaowei",30);
Student s3 = new Student("xiaoluo",22);
```arrayList.add(s1);
arrayList.add(s2);
arrayList.add(s3);
System.out.println(arrayList.size());//结果为3
System.out.println(arrayList.toString()); //结果为[Student{name='xiaoming', age=21}, Student{name='xiaowei', age=30}, Student{name='xiaoluo', age=22}]
```

```java
ArrayList arrayList = new ArrayList();

Student s1 = new Student("xiaoming",21);
Student s2 = new Student("xiaowei",30);
Student s3 = new Student("xiaoluo",22);
arrayList.remove(s1);//正常用法

System.out.println(arrayList.size());
```

```java
arrayList.remove(new Student("xiaoming",21));//注意想用这种方法要进行方法的重写!!!
```
重写!!!为什么?我以为是在实现代码中new的是一个新的对象,不是原有的对象,位置不一样,所以如果是不进行重写的话,是remove不了的!!!
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210509113558959.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2x1b2h6eno=,size_16,color_FFFFFF,t_70#pic_center)
## Iterator、ListIterator

```java
ArrayList arrayList = new ArrayList();

Student s1 = new Student("xiaoming",21);
Student s2 = new Student("xiaowei",30);
Student s3 = new Student("xiaoluo",22);
Iterator q1 = arrayList.iterator();
while (q1.hasNext()){
Student student = (Student) q1.next();
System.out.println(student.toString());
}
//ListIterator
ListIterator q2 = arrayList.listIterator();
while (q2.hasNext()){
Student student = (Student) q1.next();
System.out.println(student.toString());
}
```
## 判断、查看位置---->contains、isEmpty、indexOf

```java
ArrayList arrayList = new ArrayList();

Student s1 = new Student("xiaoming",21);
Student s2 = new Student("xiaowei",30);
Student s3 = new Student("xiaoluo",22);
System.out.println(arrayList.contains(s1));
System.out.println(arrayList.isEmpty());
//查看位置---->indexOf
System.out.println(arrayList.indexOf(s1));
```

posted on 2021-05-09 11:45  luohzzz  阅读(60)  评论(0编辑  收藏  举报