List类集接口-ArrayList

Collection接口下的List子接口允许有重复,那么在实际的开发之中,90%都使用的List接口。

List接口对Collection接口做了大量的扩充,主要扩充了如下方法:

public E set(int index, E element) 普通 修改指定索引的数据
public E get(int index) 普通 取得指定索引的数据
public ListIterator<E> listIterator() 普通 为ListIterator接口实例化

List中有三个子类:ArrayList(90%)、LinkedList(5%)、Vector(5%)。

1.使用ArrayList实例化List接口

 1 package cn.demo;
 2 
 3 import java.util.ArrayList;
 4 import java.util.List;
 5 
 6 public class TestHash {
 7     public static void main(String[] args) throws Exception {
 8         List<String> set = new ArrayList<String>();
 9         set.add("java");
10         set.add("html"); 
11         set.add("jsp"); 
12         set.add("ajax"); 
13         System.out.println(set);
14         System.out.println(set.get(2));
15         System.out.println(set.contains("java"));
16         Object obj [] = set.toArray() ; // 不可能使用 
17         for (int x = 0 ; x < obj.length ; x ++) {
18             System.out.println(obj[x]);
19         }
20     }
21 }

 结果:

[java, html, jsp, ajax]
jsp
true
java
html
jsp
ajax

2.List与简单Java类:

对于List集合(所有集合)如果要想实现数据的删除与查找操作,一定需要简单java类中的equals()方法支持。

 1 package cn.demo;
 2 
 3 import java.util.ArrayList;
 4 import java.util.List;
 5 
 6 class Phone{
 7     private String name;
 8     private double price;
 9     public Phone(String name,double price){
10         this.name =name;
11         this.price = price;
12     }
13     
14     @Override
15     public String toString() {
16         return "Phone [name=" + name + ", price=" + price + "/n";
17     }
18     
19     @Override
20     public boolean equals(Object obj) {
21         if (this == obj)
22             return true;
23         if (obj == null)
24             return false;
25         if (getClass() != obj.getClass())
26             return false;
27         Phone other = (Phone) obj;
28         if (name == null) {
29             if (other.name != null)
30                 return false;
31         } else if (!name.equals(other.name))
32             return false;
33         if (Double.doubleToLongBits(price) != Double.doubleToLongBits(other.price))
34             return false;
35         return true;
36     }
37 }
38 public class TestDemo {
39     public static void main(String[] args) {
40         List<Phone> all = new ArrayList<Phone>();
41         all.add(new Phone("xiao米",20.9));
42         all.add(new Phone("大米",20));
43         System.out.println(all.contains(new Phone("大米",20)));
44         all.remove(new Phone("xiao米",20.9));
45         System.out.println(all);
46     }
47 }

结果:

true
[Phone [name=大米, price=20.0/n]

Collection类集删除对象或查找对象一定要使用equals()方法。

原文地址:https://www.cnblogs.com/liyang31/p/5811914.html