文章目录
- Collection接口和常用方法(以ArrayList为例)
- 基本使用方法
- 遍历元素方式1(iterator)
- 遍历元素方式2(增强for)
- 练习
Collection接口和常用方法(以ArrayList为例)
以ArrayList,其他集合同理使用
基本使用方法
注:集合添加基本数据类型会自动装箱成对象
https://www.runoob.com/java/java-arraylist.html
遍历元素方式1(iterator)
https://www.runoob.com/java/java-iterator.html
遍历元素方式2(增强for)
增强for底层就是迭代器
https://www.runoob.com/java/collection-iterator.html
练习
1.创建3个Dog {name, age}对象,放入到 ArrayList 中,赋给List 引用
2.用迭代器和增强for循环两种方式来遍历
3.重写Dog的toString方法,输出name和age
package Collection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
class Dog{
private String name;
private int age;
public Dog(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {return name;}
public void setName(String name) {this.name = name;}
public int getAge() {return age;}
public void setAge(int age) {this.age = age;}
@Override
public String toString() {
return "Dog{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
public class Collection_ {
@SuppressWarnings({"all"})//警告不提醒
public static void main(String[] args) {
List list = new ArrayList();
list.add(new Dog("A",10));
list.add(new Dog("B",6));
list.add(new Dog("C",4));
list.add(new Dog("D",11));
System.out.println("1、使用迭代器遍历");
Iterator it = list.iterator();
while (it.hasNext()) {
Object next = it.next();
System.out.println(next);
}
System.out.println("2、使用增强for遍历");
for (Object obj:list){
System.out.println(obj);
}
}
}