Java泛型
规范容器类的数据类
容器<数据类型>
package org.Generic;
import java.util.ArrayList;
import java.util.List;
public class demo01 {
public static void main(String[] args) {
List<String> strlist = new ArrayList<String>();
strlist.add("simple");
strlist.add("123");
String s = strlist.get(1);
System.out.println(s);
}
}
set 和List的泛型是一样的
Map的泛型不一样
package org.Generic;
import java.util.HashMap;
import java.util.Map;
public class demo02 {
public static void main(String[] args) {
Map<String,String> map = new HashMap<String,String>();
map.put("1","simple");
map.put("2","simple2");
String s = map.get("1");
System.out.println(s);
}
}
增强for
语法:
for(类型 变量:数组或集合){
循环体
}
package org.For;
import java.sql.Array;
import java.util.ArrayList;
import java.util.LinkedList;
public class demo01 {
public static void main(String[] args) {
String[] arr = {"simpel","complex","1","2"};
// for (int i = 0; i < arr.length; i++) {
// System.out.println(arr[i]);
// }
// 增强for
for (String s:arr) {
System.out.println(s);
}
ArrayList<String> list = new ArrayList<>();
list.add("1");
list.add("2");
list.add("3");
list.add("4");
for (String s : list) {
System.out.println(s);
}
}
}