List类集接口-ArrayList
生活随笔
收集整理的這篇文章主要介紹了
List类集接口-ArrayList
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
Collection接口下的List子接口允許有重復(fù),那么在實(shí)際的開(kāi)發(fā)之中,90%都使用的List接口。
List接口對(duì)Collection接口做了大量的擴(kuò)充,主要擴(kuò)充了如下方法:
| public E set(int index, E element) | 普通 | 修改指定索引的數(shù)據(jù) |
| public E get(int index) | 普通 | 取得指定索引的數(shù)據(jù) |
| public ListIterator<E> listIterator() | 普通 | 為L(zhǎng)istIterator接口實(shí)例化 |
List中有三個(gè)子類:ArrayList(90%)、LinkedList(5%)、Vector(5%)。
1.使用ArrayList實(shí)例化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 }?結(jié)果:
[java, html, jsp, ajax]
jsp
true
java
html
jsp
ajax
2.List與簡(jiǎn)單Java類:
對(duì)于List集合(所有集合)如果要想實(shí)現(xiàn)數(shù)據(jù)的刪除與查找操作,一定需要簡(jiǎn)單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 }結(jié)果:
true
[Phone [name=大米, price=20.0/n]
Collection類集刪除對(duì)象或查找對(duì)象一定要使用equals()方法。
轉(zhuǎn)載于:https://www.cnblogs.com/liyang31/p/5811914.html
總結(jié)
以上是生活随笔為你收集整理的List类集接口-ArrayList的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: NULL,,String.Empty三者
- 下一篇: zabbix3.0.4 部署之一 (简介