naturalCloud naturalCloud

记录精彩的程序人生

目录
java:复杂数据 类型
/    

java:复杂数据 类型

复杂数据类型创建遍历

array 和 ArrayList

array

  • 固定长度数组

ArrayList

  • 动态数组
 1  //声明25个元素的数组
 2        int[] num = new int[25];
 3        //初始化 长度3的字符窜数组
 4        String[] str = {"a", "b", "c"};
 5        //遍历
 6        for (int i = 0; i < 25; i++) {
 7            num[i] = i * 3;
 8
 9        }
10        for (int n : num) {
11            System.out.println(n);
12        }
13        //遍历
14        for (String s : str) {
15            System.out.printf("%s", s);
16        }
17
18ArrayList<String> list = new ArrayList<>();
19        list.add("abc");
20        list.add("dddd");
21
22        //for循环遍历
23        for (String s : list) {
24            System.out.println(s + "");
25        }
26
27        //迭代器遍历
28
29        Iterator<String> iterator = list.iterator();
30        while (iterator.hasNext()) {
31            System.out.println("迭代器遍历 " + iterator.next());
32        }
33
34        //索引遍历
35
36        for (int i = 0; i < list.size(); i++) {
37            System.out.println("索引遍历 key " + i + " value " + list.get(i));
38
39        }
40
41   //ArrayList 转为数组
42        String[] strings = list.toArray((new String[0])); //常用
43        String[] strings1 = new String[list.size()];//容易理解
44        
45        //移除某个元素
46        list.remove(1); 
47        list.clear();//清空数组
48        
49        System.out.println(list);
50

HashMap 和 HashTable

 1
 2//创建map
 3  HashMap<String, String> map = new HashMap<>();
 4        map.put("test1", "wacx");
 5        map.put("test2", "wwww");
 6
 7       //1 遍历 
 8        for (Map.Entry<String, String> entry : map.entrySet()) {
 9
10            System.out.println("key = " + entry.getKey() + " value = " + entry.getValue());
11        }
12
13   
14      // 2 分别遍历key value 
15        for ( String key :map.keySet()) {
16            System.out.printf("key %s \n" ,key);
17        }
18
19        for (String value : map.values()) {
20            System.out.printf("值 %s \n",value);
21        }
22
23          //使用迭代器
24        Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
25
26        while (iterator.hasNext()) {
27            Map.Entry<String, String> next = iterator.next();
28            System.out.printf("key %s value %s \n",next.getKey(),next.getValue());
29        }
30
31
32

标题:java:复杂数据 类型
作者:naturalCloud
地址:https://yunqiblog.cn/articles/2020/02/18/1582032805228.html