徐州做汽車銷售的公司網(wǎng)站企業(yè)網(wǎng)站建設(shè)平臺
List不同實(shí)現(xiàn)類的對比
文章目錄
- List不同實(shí)現(xiàn)類的對比
- 實(shí)現(xiàn)類之一`ArrayList`
- 實(shí)現(xiàn)類之二 `LinkedList`
- 實(shí)現(xiàn)類之三 `Vector`
- 練習(xí)
java.util.Collection
用于存儲一個一個數(shù)據(jù)的框架- 子接口:
List
存儲有序的、可重復(fù)的數(shù)據(jù)(相當(dāng)于動態(tài)數(shù)組)
ArrayList
list的主要實(shí)現(xiàn)類(線程不安全、效率高) 底層使用Object[]
的數(shù)組存儲。添加數(shù)據(jù)、查找數(shù)據(jù)時,效率較高;插入數(shù)據(jù)、刪除數(shù)據(jù)時,效率較低Vector
List的古老實(shí)現(xiàn)類 (線程安全、效率低) 底層使用Object[]
數(shù)組存儲LinkedList
底層使用雙向鏈表的方式進(jìn)行存儲。插入數(shù)據(jù)、刪除數(shù)據(jù)時效率較高;添加數(shù)據(jù)、查找數(shù)據(jù)時,效率較低。
實(shí)現(xiàn)類之一ArrayList
-
ArrayList 是 List 接口的
主要實(shí)現(xiàn)類
-
本質(zhì)上,ArrayList是對象引用的一個”變長”數(shù)組
-
Arrays.asList(…) 方法返回的 List 集合,既不是 ArrayList 實(shí)例,也不是 Vector 實(shí)例。 Arrays.asList(…) 返回值是一個固定長度的 List 集合
實(shí)現(xiàn)類之二 LinkedList
對于頻繁的插入或刪除元素的操作,建議使用LinkedList類,效率較高。這是由底層采用鏈表(雙向鏈表)結(jié)構(gòu)存儲數(shù)據(jù)決定的。
特有方法:
- void addFirst(Object obj)
- void addLast(Object obj)
- Object getFirst()
- Object getLast()
- Object removeFirst()
- Object removeLast()
實(shí)現(xiàn)類之三 Vector
- Vector 是一個
古老
的集合,JDK1.0就有了。大多數(shù)操作與ArrayList相同,區(qū)別之處在于Vector是線程安全
的。 - 在各種List中,最好把
ArrayList作為默認(rèn)選擇
。當(dāng)插入、刪除頻繁時,使用LinkedList;Vector總是比ArrayList慢,所以盡量避免使用。 - 特有方法:
- void addElement(Object obj)
- void insertElementAt(Object obj,int index)
- void setElementAt(Object obj,int index)
- void removeElement(Object obj)
- void removeAllElements()
練習(xí)
鍵盤錄入學(xué)生信息,保存到集合List中
- 定義學(xué)生類。存在姓名、年齡的屬性
- 使用ArrayList集合,保存錄入的多個學(xué)生對象
- 循環(huán)錄入方式
- 錄入結(jié)束后,用迭代器遍歷
//學(xué)生類 public class Student {private String name;private int age;public Student(String name, int age) {this.name = name;this.age = age;}public Student(){}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}@Overridepublic String toString() {return "Student{" +"name='" + name + '\'' +", age=" + age +'}';}@Overridepublic boolean equals(Object o) {if (this == o) return true;if (o == null || getClass() != o.getClass()) return false;Student student = (Student) o;return age == student.age && Objects.equals(name, student.name);}@Overridepublic int hashCode() {return Objects.hash(name, age);} }
//Test類 import java.util.ArrayList; import java.util.Scanner;public class StudentTest {public static void main(String[] args) {Scanner input = new Scanner(System.in);ArrayList list = new ArrayList();System.out.println("請錄入學(xué)生信息:");while(true){System.out.println("1,繼續(xù)錄入 0.結(jié)束錄入");int selection = input.nextInt();if(selection == 0){break;}System.out.println("請輸入學(xué)生的姓名:");String name = input.next();System.out.println("請輸入學(xué)生的年齡");int age = input.nextInt();Student s = new Student(name,age);list.add(s);}//遍歷集合中的學(xué)生信息System.out.println("遍歷學(xué)生信息");for(Object s : list){System.out.println(s.toString());}input.close();} }