list集合(it技术讨论群号:317569206)

  List作为Collection接口的子接口,可以使用collection里的所有方法。由于List是有序集合,因此List集合里增加了一些根据索引来操作集合元素的方法。

①void(int index,Object element):将元素element插入到List集合的index处。

②boolean addAll(int index,Collection c):将c集合包含的所有元素插入到List集合的index处。

③Object get(int index):返回集合index索引处的元素。

④int indexOf(Object o):返回对象o在list集合中第一次出现的位置索引。

⑤int lastIndexOf(Object o):返回对象o在list集合中最后一次出现的位置索引。

⑥Object remove(int index):删除并返回index索引处的元素。

⑦Object set(index,element):将index索引处的元素替换成element对象,返回被替换的旧元素。

⑧List subList(int fromIdex,int toIndex):返回从索引fromIndex(包含)到索引toIndex(不包含)处所有集合元素组成的子集合。

  所有的List实现类都可以调用这些方法来操作集合元素,与set集合相比,List增加了根据索引来插入、替换和删除集合元素的方法。除此之外,Java8还为List接口添加了如下两个默认方法。

①void replaceAll(UnaryOperator operator):根据operator指定的计算规则重新设置List集合的所有元素

②viod sort(Comparator c):根据Comparator参数对List集合的元素排序。

  下面程序示范了List集合的常规用法:

 1 public class ListTest{
 2       public static viod main(String[]args){
 3             List books=new ArraryList();
 4             //向books集合中添加3个元素
 5             books.add(new String("第一个元素"));  
 6             books.add(new String("第二个元素"));  
 7             books.add(new String("第三个元素"));  
 8             System.out.println(books);
 9             //将新字符串对象插入到第二个位置
10             books.add(1,new String("新对象1"));
11             for(int i=0;i<books.size;i++){
12                  System.out.println(books.get(i));
13         }
14             //删除第三个数据
15             books.remove(2);
16             system.out.println(books);
17             //判断指定元素在list集合中的位置:输出1,表明位于第二位
18             System.out.println(books.indexOf(new String("新对象 1")));
19             //将第二个元素替换成新的字符串对象
20             books.set(1,new String("第二个元素"));
21             System.out.println(books);
22             //将books集合的第二个元素(包括)到第三个元素(不包括)截取成子集合
23             System.out.println(books.subList(1,2));
24     }
25 }

  List判断两个对象相等只要通过equals()方法比较返回true即可,程序如下

 1 class A{
 2     public boolean equals(Object obj){
 3         return true;
 4     }
 5 }
 6 public class ListTest2{
 7     public static viod main(String[]args){
 8          List books=new ArraryList();
 9          books.add(new String("第一个元素"));  
10          books.add(new String("第二个元素"));  
11          books.add(new String("第三个元素"));  
12          System.out.println(books);
13          //删除集合中的A对象,将导致第一个对象被删
14          books.remove(new(A));
15          System.out.println(books);
16          //删除集合中的A对象,再次删除集合中的第一个元素
17          books.remove(new(A));
18          System.out.println(books);
19     }
20 }

上述代码A类重写了equals()方法,该方法总是返回true,所以每次从List集合中删除A对象,总是删除List集合中的第一个元素

posted on 2017-03-16 10:11  吃不饱  阅读(124)  评论(0)    收藏  举报

导航