数组,json,List,Map的初始化、取值和遍历记录

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));
}

}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值