ArrayList的使用
生活随笔
收集整理的這篇文章主要介紹了
ArrayList的使用
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
概念:
ArrayList是一種有序可變的容器,ArrayList構(gòu)造會自動創(chuàng)建長度為10的容器,超過10會自動增加
集合和數(shù)組的區(qū)別 :
? 共同點:都是存儲數(shù)據(jù)的容器
? 不同點:數(shù)組的容量是固定的,集合的容量是可變的
集合底層也是數(shù)組,數(shù)組的效率會更好,但是功能有限,如果要存儲的數(shù)據(jù)經(jīng)常發(fā)生變化就使用集合
ArrayList的構(gòu)造方法和成員方法:
| public boolean add(E e) | 將指定的元素追加到此集合的末尾 |
| public void add(int index,E element) | 在此集合中的指定位置插入指定的元素 |
| public boolean remove(Object o) | 刪除指定的元素,返回刪除是否成功 |
| public E remove(int index) | 刪除指定索引處的元素,返回被刪除的元素 |
| public E set(int index,E element) | 修改指定索引處的元素,返回被修改的元素 |
| public E get(int index) | 返回指定索引處的元素 |
| public int size() | 返回集合中的元素的個數(shù) |
鍵盤錄入學生信息到集合:
public static void main(String[] args) {//創(chuàng)建集合對象ArrayList<Student> array = new ArrayList<Student>();//為了提高代碼的復用性,我們用方法來改進程序addStudent(array);//遍歷集合,采用通用遍歷格式實現(xiàn)for (int i = 0; i < array.size(); i++) {Student s = array.get(i);System.out.println(s.getName() + "," + s.getAge());}}public static void addStudent(ArrayList<Student> array) {//鍵盤錄入學生對象所需要的數(shù)據(jù)Scanner sc = new Scanner(System.in);System.out.println("請輸入學生姓名:");String name = sc.nextLine();System.out.println("請輸入學生年齡:");int age = sc.nextInt();//創(chuàng)建學生對象,把鍵盤錄入的數(shù)據(jù)賦值給學生對象的成員變量Student student = new Student(name, age);//往集合中添加學生對象array.add(s);}刪除注意:
public static void main(String[] args) {// 創(chuàng)建集合ArrayList<String> list = new ArrayList<>();list.add("abc");list.add("123");list.add("123");list.add("45126");list.add("654");for (int i = 0; i < list.size(); i++) {String s = list.get(i);// 盡量用常量調(diào)equals,不要用變量if ("123".equals(s)) {list.remove(i);/**不做--的話就會有遺漏,實現(xiàn)的原理是:刪除第一個指定元素以后,往后面判斷的時候,所有的元素的素索引都會往前移動,當指針走到索引1,這時候索引1是第一個123,把它刪掉了,然后從索引2整體向前移動,現(xiàn)在的索引1是第二個123,這時候指針又開始了++。就剛好錯過了第二個123。如果加上--,在刪除以后就會回退一個索引,然后循環(huán)又++,就不會錯過了*/i--;}}System.out.println(list);}集合篩選:
public static void main(String[] args) {ArrayList<Student> list = new ArrayList<>();Student stu1 = new Student("韓信", 2);Student stu2 = new Student("李白", 23);Student stu3 = new Student("露娜", 24);list.add(stu1);list.add(stu2);list.add(stu3);ArrayList<Student> newList = getList(list);for (int i = 0; i < newList.size(); i++) {Student student = newList.get(i);System.out.println(student.getName() + ":" + student.getAge());}}private static ArrayList<Student> getList(ArrayList<Student> list) {// 創(chuàng)建新集合ArrayList<Student> newlist = new ArrayList<>();// 遍歷集合,獲取每一個學生對象for (int i = 0; i < list.size(); i++) {Student stu = list.get(i);// 調(diào)用getage判斷年齡是否小于18int age = stu.getAge();if (age < 18) {// 把年齡小于18的學生存到新集合newlist.add(stu);}}return newlist;}總結(jié)
以上是生活随笔為你收集整理的ArrayList的使用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 中的数组怎么转成结构体_传说中的“衡水体
- 下一篇: 转换流/序列化/反序列化