List 集合是有序的, 可重复的元素. 里面每个元素都有索引, 通过索引访问元素.
List 接口是 Colletion 的子接口, 自然可以用里面的方法. 额外的增加了通过索引访问集合元素的方法. 如下
- package Test01;
- import java.util.ArrayList;
- import java.util.List;
- public class TestList { public static void main(String[] args) {
- List l =new ArrayList();
- List m =new ArrayList();
- m.add(new String("新的集合元素"));
- l.add(new String("eee"));
- l.add(new String("qqq"));
- System.out.println("第一次"+l);
- l.add(1, new String("啦啦啦")); // 在指定索引处添加元素
- l.add(2, new String("啦啦啦"));
- System.out.println("第二次"+l);
- for(int i=0;i<l.size();i++) {
- System.out.println("每个元素分别为"+l.get(i));
- }
- l.remove(0); // 删除指定 Index
- l.subList(0, 1);
- l.addAll(m);
- System.out.println(l);
- System.out.println(l.indexOf(new String("啦啦啦")));
- System.out.println(l.lastIndexOf(new String("啦啦啦")));
- }
- }
上面的常见的
还有 void sort(Comparator comparator); 将 Comparator 规则给 List 排序
void replaceAll(UnaryOperation operator) 重新用 operator 计算规则给 List 排序
那类比得, List 判断集合元素相等的条件是什么呢? equals 返回 true
以下例子重写了 equals, 看看得出什么结论
- package Test01;
- import java.util.ArrayList;
- import java.util.List;
- class A{
- @Override
- public boolean equals(Object obj) {
- // TODO Auto-generated method stub
- return true;
- }
- }
- public class TestList {
- public static void main(String[] args) {
- List l =new ArrayList();
- l.add(new String("eee"));
- l.add(new String("qqq"));
- System.out.println("删除前"+l);
- l.remove(new A());
- System.out.println("删除后"+l);
- }
- }
List 集合试图删除一个 A 对象, 竟然删除了第一个元素. 因为打算删除 A 时, 调用了 equals 方法, 和集合里的其他元素比较, 返回 true, 就删除那个元素.
与 Set 集合不同只提供了一个
待续....
来源: http://www.bubuko.com/infodetail-2671330.html