数组,只能声明已知长度的,哪怕是二维也是必须声明行数
所以引入ArrayList,HashMap(键值对形式),对可变长度的数据进行存储
import java.util.*;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
//常规数组声明
int Max_Size= 20;
int num[] = new int[Max_Size]; //方式一
num[0] = 10;
num[1] = 11;
int[] num1 = {1,3,4,5}; //方式二
// System.out.println(num1[0]);
// System.out.println(num[19]);
//List创建,可变长度数组,并且遍历
//遍历 ArrayList 方式一
List<String> list = new ArrayList<String>();
list.add("Hello");
list.add(1, "World");
for(String item : list){
System.out.println(item);
}
System.out.println("List转数组");
//遍历 ArrayList 方式二
String[] list_ = new String[list.size()];
list.toArray(list_);
for(String item : list_){
System.out.println(item);
}
//遍历 ArrayList 方式三
System.out.println("迭代器");
Iterator<String> ite = list.iterator();
while(ite.hasNext()){
System.out.println(ite.next());
}
//Map创建,遍历
Map<String,String> map = new HashMap<String,String>();
map.put("1", "Hello");
map.put("2", "Map");
System.out.println("Map.keySet");
for(String key : map.keySet()){
System.out.println("key=" + key + " value=" + map.get(key));
}
System.out.println("Map.entrySet iterator");
Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
while(it.hasNext()){
Map.Entry<String, String> entry = it.next();
System.out.println("key=" + entry.getKey() + " value=" + entry.getValue());
}
System.out.println("Map.entrySet");
for(Map.Entry<String, String> entry : map.entrySet()){
System.out.println("key=" + entry.getKey() + " value=" + entry.getValue());
}
System.out.println("Map.values");
for (String value : map.values()) {
System.out.println("value=" + value);
}
}
}
Hello
World
List转数组
Hello
World
迭代器
Hello
World
Map.keySet
key=1 value=Hello
key=2 value=Map
Map.entrySet iterator
key=1 value=Hello
key=2 value=Map
Map.entrySet
key=1 value=Hello
key=2 value=Map
Map.values
value=Hello
value=Map
网友评论