本文整理的是优快云博主「vaniice」的原创文章。
原文链接
1.使用
1.1 List接口的常用实现类
在使用List集合时,通常情况下声明为List类型,实例化时根据实际情况的需要,实例化为ArrayList或LinkedList,例如:
List<String> list1= new ArrayList<String>();// 利用ArrayList类实例化List集合
List<String> list2 = new LinkedList<String>();// 利用LinkedList类实例化List集合
1.2 List接口所提供的方法:
<1> add(int index, Object obj) 指定索引位置添加对象
<2> addAll(int index, Collection coll) 指定索引位置添加集合中所有对象,如果列表发生改变则返回true。index是可选的,默认为添加到尾部。
例如,有列表list
和list_add
,将list
中全部对象添加到list_add
的尾部:
List<String> list = new ArrayList<String>();
list.add("保护环境"); //向列表中添加数据
list.add("爱护地球"); //向列表中添加数据
list.add("从我做起"); //向列表中添加数据
List<String>list_ad = new ArrayList<String>();
list_ad.add("公益广告");
System.out.println("是否添加成功:"+list_ad.addAll(list)); //通过循环输出列表中的内容
for(int i=0;i<list_ad.size();i++){
System.out.println(i+":"+list_ad.get(i));
}
输出结果:
是否添加成功:true
0:公益广告
1:保护环境
2:爱护地球
3:从我做起
该示例引用自:http://c.biancheng.net/view/4727.html
<3> remove(int index) 删除指定位置的对象
<4> set(int index, Object obj) 修改指定索引位置的对象
<5> get(int index) 获取指定索引位置的对象
<6> indexOf(Object obj) 获取指定对象的(第一个)索引位置
<7> lastIndexOf(Object obj) 获取指定对象的(最后一个)索引位置
<8> listIterator(int index) 获取从指定索引位置到最后的LisrIterator型实例
<9> subList(int fromIndex, int toIndex) 截取从(包含)起始索引到(不包含)终止索引的对象,返回List集合
2.练习
力扣题库:1773. 统计匹配检索规则的物品数量
2.1 题目描述
给你一个数组 items ,其中 items[i] = [typei, colori, namei] ,描述第 i 件物品的类型、颜色以及名称。
另给你一条由两个字符串 ruleKey 和 ruleValue 表示的检索规则。
如果第 i 件物品能满足下述条件之一,则认为该物品与给定的检索规则 匹配 :
- ruleKey == “type” 且 ruleValue == typei 。
- ruleKey == “color” 且 ruleValue == colori 。
- ruleKey == “name” 且 ruleValue == namei 。
统计并返回 匹配检索规则的物品数量 。
示例 1:
输入:items =
[[“phone”,“blue”,“pixel”],[“computer”,“silver”,“lenovo”],[“phone”,“gold”,“iphone”]],
ruleKey = “color”, ruleValue = “silver”
输出:1
解释:只有一件物品匹配检索规则,这件物品是
[“computer”,“silver”,“lenovo”] 。
示例 2:
输入:items =
[[“phone”,“blue”,“pixel”],[“computer”,“silver”,“phone”],[“phone”,“gold”,“iphone”]],
ruleKey = “type”, ruleValue = “phone”
输出:2
解释:只有两件物品匹配检索规则,这两件物品分别是
[“phone”,“blue”,“pixel”] 和 [“phone”,“gold”,“iphone”]
注意,[“computer”,“silver”,“phone”] 未匹配检索规则。
提示:
1 <= items.length <= 10^4
1 <= typei.length, colori.length,namei.length, ruleValue.length <= 10
ruleKey 等于 “type”、“color” 或 “name”
所有字符串仅由小写字母组成
2.2 代码
class Solution {
public int countMatches(List<List<String>> items, String ruleKey, String ruleValue) {
int j = 0;
if(ruleKey.equals("color")){
j = 1;
}else if(ruleKey.equals("name")){
j = 2;
}
int num = 0;
for(int i = 0;i <items.size(); i++){
if(items.get(i).get(j).equals(ruleValue)){
num = num + 1;
}
}
return num;
}
}