List类集接口-ArrayList
生活随笔
收集整理的這篇文章主要介紹了
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
總結
以上是生活随笔為你收集整理的List类集接口-ArrayList的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: NULL,,String.Empty三者
- 下一篇: zabbix3.0.4 部署之一 (简介