集合+泛型
ArrayList常见泛型和特殊泛型的使用
ArrayList特点
1:存储有序 基于数组 长度可变
2:因为基于数组 便利方便 删除那麻烦(需要移动)
java
package com.it.arraylist;
import java.util.ArrayList;
import java.util.Iterator;
/**
* @Date 2019/8/8 16:22
* @Created by hfh
* @Description
* ArrayList 常见类型泛型和特殊类型练习
* 特点 1:相同元素可以重复存储
* 2:便利方便 删除不方便
*/
public class ArrayListTest {
public static void main(String[] args) {
//创建常见对象
ArrayList<String> arrayList = new ArrayList<>();
//创建特殊类型泛型arrayList对象
ArrayList<Student> arrayList1 = new ArrayList<Student>();
System.out.println("---------------常见类型泛型以String为例-----------------");
//添加元素
arrayList.add("周星驰");
arrayList.add("张国荣");
arrayList.add("周润发");
arrayList.add("冰冰");
arrayList.add("张国荣");//[周星驰, 张国荣, 周润发, 冰冰, 张国荣]
// 看出是按照顺序存储,且元素可以重复。
System.out.println(arrayList.toString());
//删除
//arrayList.remove(1);//可以按照元素只删除 也可以按照索引删除
System.out.println(arrayList.toString());//[周星驰, 周润发, 冰冰, 张国荣]
//遍历
System.out.println("------------增强for遍历----------------------");
for (String s : arrayList) {
System.out.println(s);
}
System.out.println("---------------for遍历-----------------------");
int len = arrayList.size();
for (int i = 0; i < len; i++) {
System.out.println(arrayList.get(i));
}
System.out.println("----------------迭代器遍历---------------------------");
Iterator iterator = arrayList.iterator();//Iterator为接口不可以创建实例
while (iterator.hasNext()){
System.out.println(iterator.next());
}
System.out.println("----------------------特殊类型泛型练习----------------------");
//创建特殊类型对象
Student student1 = new Student();
Student student2 = new Student();
Student student3 = new Student();
Student student4 = new Student();
Student student5 = new Student();
Student student6 = new Student();
//添加 添加之前得有Student对象
arrayList1.add(student1);
arrayList1.add(student2);
arrayList1.add(student3);
arrayList1.add(student4);
arrayList1.add(student5);
arrayList1.add(student6);
System.out.println(arrayList1.toString());//因为此时toString为Object类的方法
// 特殊类型的toString就需要重写 才能打印想要看到的结果
//删除
arrayList1.remove(2);//同样可以按照索引和元素值进行删除
System.out.println(arrayList1.toString());
//遍历
System.out.println("------------增强for遍历----------------------");
for (Student student : arrayList1) {
System.out.println(student);
}
System.out.println("---------------for遍历-----------------------");
int a = arrayList1.size();
for (int i = 0; i < a; i++) {
System.out.println(arrayList1.get(i));
}
//剩余遍历方式同上
}
}
```java
package com.it.arraylist;
/**
* @Date 2019/8/8 16:28
* @Created by hfh
* @Description TODO
*/
public class Student {
//属性封装
private int age;
private String name;
//构造方法
public Student() {
}
public Student(int age, String name) {
this.age = age;
this.name = name;
}
//getter setter暴露私有属性 规定属性规范 保证安全
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Student{" +
"age=" + age +
", name='" + name + '\'' +
'}';
}
}