泛型的基本知识点及应用

基本知识

声明

以 ArrayList 为例:

// 创建空的 Float 容器
ArrayList<Float> alist = new ArrayList<Float>();  
// 创建指定大小的 String 容器
ArrayList<String> strList = new ArrayList<String>(10);

添加

alist.add(0.25);
strList.add("test");

遍历

// for 遍历
for (int i = 0; i < strList.size(); i++)
  str += strList.get(i);

// foreach 遍历
for (String ele : strList)
  str += ele;

ArrayList 与 map 结合

// 使用 ArrayList 作为数据容器,其中的每一项都是 HashMap<String, Object>

// 声明
ArrayList<HashMap<String, Object>> PayItems;

// 新建
PayItems = new ArrayList<HashMap<String, Object>>();

// 插入
HashMap<String, Object> map = new HashMap<String,Object>();

map.put("rownum", PayItems.size() + 1);
map.put("name", strName);
map.put("nameid", NameId);
map.put("date", edtDate.getText().toString().trim());
map.put("pay", Integer.parseInt(strPay));

PayItems.add(map);

// 读取
// 遍历容器中每一项,将其写入数据库
ContentValues cv = new ContentValues();
for (HashMap<String, Object> i : PayItems) {
    cv.clear();
    cv.put("pid", (Long)i.get("nameid"));
    cv.put("pay", (Integer)i.get("pay"));
    cv.put("shiyou", (String)i.get("shiyou"));
    cv.put("date", (Long)i.get("juliandate"));
    ret = db.insert("zhangmu", null, cv);
}
PayItems.clear();

// 遍历并修改
for (int i = 0; i < PayItems.size(); i++) {
    HashMap<String, Object> item = PayItems.get(i);
    String strName = (String)item.get("name");
    if (strName == 'Tom') {
        int pay = (int)item.get("pay");
        item.remove("pay");
        item.put("pay", pay + 1000);
        PayItems.set(i, item);
    }
}

// 排序
Collections.sort(PayItems, new Comparator<HashMap<String, Object>>(){
	@Override
	public int compare(HashMap<String, Object> item1, HashMap<String, Object> item2) {
		String str1 = (String)item1.get("name");
		String str2 = (String)item2.get("name");
		// 根据姓名长度降序排列,返回正值表示需要交换两个元素
		return str2.length() - str1.length();
	}
});

// 查找,没有捷径,只能遍历
posted @ 2022-02-26 09:13  汉学  阅读(27)  评论(0)    收藏  举报