1、数组
/*
* @author willon
* 数组遍历demo
* 数组的初始化必须有固定长度
*/
public class ArraytraversalDemo {
public static void main(String[] args) {
// 未赋值的初始化
String[] array1 = new String[3];
// 赋初值的初始化
String[] array2 = {"1","2,","c"};
// 数组赋值
array1[0] = "c";
array1[1] = "b";
array1[2] = "a";
// 数组重新赋值
array2[0] = "x";
// 数组取值
String index_value = array1[1];
// 普通for循环遍历
for(int i = 0 ; i< array1.length;i++){
System.out.println("array1的第"+(i+1)+"个值"+array1[i]);
}
// 增强for循环遍历
for(String value : array2){
System.out.println(value);
}
}
}
2. Json
import java.util.Iterator;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
/*
* @author Wilon.C
*
*/
public class JsonTraversalDemo {
public static void main(String[] args) {
// 定义两个String,分别为json格式,个jsonArray格式
String json = "{\"Name\":\"Wilon\",\"Age\":\"18\",\"Sex\":\"male\"}";
String jsonA = "[{\"Name\":\"Wilon\",\"Age\":\"18\",\"Sex\":\"male\"},{\"Name\":\"Wilon1\",\"Age\":\"16\",\"Sex\":\"male\"},{\"Name\":\"Wilon2\",\"Age\":\"120\",\"Sex\":\"female\"}]";
//
JSONObject jo = JSONObject.fromString(json);
JSONObject jsonDemo = null;
jsonDemo.put("key", "value");
Iterator<?> it = jo.keys();
while (it.hasNext()) {
String key = it.next().toString();
System.out.println(key + ":" +jo.get(key));
}
JSONArray ja = JSONArray.fromString(jsonA);
for (int i = 0 ; i < ja.length() ; i ++){
JSONObject jsonObject = ja.getJSONObject(i);
Iterator<?> it1 = jsonObject.keys();
while (it1.hasNext()) {
String key = it1.next().toString();
System.out.println("第" + i + "个JSONObject-" + key + ":" +jsonObject.get(key));
}
}
}
}
3. List
import java.util.ArrayList;
import java.util.List;
/*
* @author Willon.C
* list的初始化不需要指定长度
*
*/
public class ListTraversalDemo {
public static void main(String[] args) {
// list的初始化
List<String> listDemo = new ArrayList<String>();
// list加值
listDemo.add("fistElement");
listDemo.add("secondElement");
listDemo.add("thirdElement");
// list取值
String index_value = listDemo.get(0);
// list遍历
for(int i = 0 ; i < listDemo.size() ; i ++){
System.out.println(listDemo.get(i));
}
// list赋值
listDemo.set(0, "new_firstElement");
// list增强for循环遍历
for(String value : listDemo){
System.out.println(value);
}
}
}
4. Map
import java.util.HashMap;
import java.util.Map;
/*
* @author Willon.C
* Map的取值是无序的,有序的可以用LinkedMap
*/
public class MapTraversalDemo {
public static void main(String[] args) {
// Map初始化
Map<String, String> mapDemo = new HashMap<String,String>();
// Map加值
mapDemo.put("key1", "value1");
mapDemo.put("key2", "value2");
mapDemo.put("key3", "value3");
// Map取值
String value1 = mapDemo.get("key1");
// Map遍历
for(String key : mapDemo.keySet()){
System.out.println(mapDemo.get(key));
}
}
}