Java中ArrayList基本用法

2022-08-25 13:08:15

ArrayList集合

特点:长度随意变化的集合,既动态数组
使用第一步导包

import java.util.ArrayList;

创建

 ArrayList<泛型> list=newArrayList<>();

泛型特例
int(Integer)
char(Character)
其余泛型均是首字母变大写 例 double(Double)

常用方法

1.添加元素

 ArrayList<Integer> list=newArrayList<>();
  list.add(1);//添加1for(int i=0; i<=10; i++){
           list.add(i);//添加0至10}

2.删除元素

list.remove(0);//删除索引为0的元素

3.获取元素

int a=list.get(0);//获取索引为0的元素

4.集合大小

int b=list.size();

5.替换元素

list.set(1,"10");// 设置第2个元素为10

6.遍历方法

for(int i=0; i< list.size(); i++){
     System.out.println(list.get(i));}

举个例子
在这里插入图片描述

publicclassPeople{private String name;privateint age;publicPeople(){}publicPeople(String name,int age){this.name= name;this.age= age;}public StringgetName(){return name;}publicvoidsetName(String name){this.name= name;}publicintgetAge(){return age;}publicvoidsetAge(int age){this.age= age;}}
publicclassdemo01{publicstaticvoidmain(String[] args){
        ArrayList<People> list=newArrayList<>();//建立一个存放类型是类的Arraylist/*
        以People为类创建三个人的对象,并赋值添加到集合当中
         */
        People people01=newPeople("小吕",20);
        People people02=newPeople("小泽",20);
        People people03=newPeople("小浩",20);
        list.add(people01);
        list.add(people02);
        list.add(people03);/*
        遍历中创建一个people对象来表示集合中的元素,从而获取到集合中的变量
         */for(int i=0; i< list.size(); i++){
            People people=list.get(i);
            System.out.println("姓名是:"+people.getName()+",年龄是:"+people.getAge());}}}
  • 作者:皓烨
  • 原文链接:https://blog.csdn.net/m0_45888043/article/details/109002343
    更新时间:2022-08-25 13:08:15