学习Java之day23
1.集合框架
一、集合框架的概述
1.集合、数组都是对多个数据进行存储操作的结构,简称Java容器。 说明:此时的存储,主要指的是内存层面的存储,不涉及到持久化的存储(.txt,.jpg,.avi,数据库中)
2.1 数组在存储多个数据方面的特点:
|----Set接口:存储无序的、不可重复的数据 -->高中讲的“集合”
|----HashSet、LinkedHashSet、TreeSet
|----Map接口:双列集合,用来存储一对(key - value)一对的数据 -->高中函数:y = f(x)
|----HashMap、LinkedHashMap、TreeMap、Hashtable、Properties
三、Collection接口中的方法的使用
### 2.foreach循环
jdk 5.0 新增了foreach循环,用于遍历集合、数组
```java
@Test
public void test1(){
Collection<Object> coll = new ArrayList();
coll.add(new String("25"));
coll.add(new Person("Tom",25));
coll.add(123);
coll.add(false);
coll.add("bao");
//for(集合元素的类型 局部变量 : 集合对象)
//内部仍然调用了迭代器。
for(Object object : coll){
System.out.print(object + "\t");
}
}
@Test
public void test2(){
int[] arr = new int[]{1, 5, 6, 8,-12};
for (int i : arr){
System.out.print(i + " " );
}
}
@Test
public void test3(){
String[] strs = new String[]{"MM","MM","MM"};
//普通for循环
for(int i=0; i<strs.length; i++){
// strs[i] = "GG";
}
//增强for循环
for (String s : strs){
s = "GG";
}
for(int i=0; i<strs.length; i++){
System.out.println(strs[i]);
}
}
//练习题
@Test
public void test4(){
String[] arr = new String[]{"MM","MM","MM"};
// //方式一:普通for赋值
// for(int i = 0;i < arr.length;i++){
// arr[i] = "GG";
// }
//方式二:增强for循环
for(String s : arr){
s = "GG";
}
for(int i = 0;i < arr.length;i++){
System.out.println(arr[i]);
}
}
3. Iterator接口
集合元素的遍历操作,使用迭代器Iterator接口
1.内部的方法:hasNext() 和 next()
2.集合对象每次调用iterator()方法都得到一个全新的迭代器对象,
默认游标都在集合的第一个元素之前。
3.内部定义了remove(),可以在遍历的时候,删除集合中的元素。此方法不同于集合直接调用remove()