Erlo

2.API简介&API的使用-ArrayList

2024-12-25 17:29:23 发布   13 浏览  
页面报错/反馈
收藏 点赞

1. API概述

  • API全称是Application Programing Interface,API中提供了多个已封装并可直接使用的类。
  • API文档是API的使用说明书。
  • java.lang中的API类无需使用import语句导入。

2. 匿名对象

  • 匿名对象是无需命名,直接使用new进行实例化的对象。

    /*定义Student.java类*/
    public class Student {
    private String name;
    
    //获取用户输入的名字
    public void setName(Scanner scan) {
        this.name = scan.next();
    }
}
        /*Main方法中输出名字*/
        Student stu = new Student();
        stu.setName(new Scanner(System.in)); //使用匿名对象作为方法参数
        System.out.println("My name is "+stu.getName());
  • 匿名对象在实例化(new)以后只能使用1次,因此匿名对象常作为方法的参数或返回值使用,用于简化操作。

3. 对象数组

  • 可把对象存放进数组中,这样的数组称为对象数组

    Student[] stuArray = new Student[5];
        stuArray[0] = new Student("python",15);
        stuArray[1] = new Student("java",16);
        stuArray[2] = new Student("linux",18);

        System.out.println(stuArray[0].getName());//输出:python
        System.out.println(stuArray[1].getAge());//输出:16

4. ArrayList

4.1 ArrayList特点

  • Array数组的长度是固定的,若要使数组长度可变,则需要使用ArrayList:

    ArrayList stuList = new ArrayList();
        stuList.add(new Student("python",15));
        stuList.add(new Student("java",16));
        stuList.add(new Student("linux",18));
        for (int i=0;i

4.2 ArrayList中的remove()方法

  • remove()方法拥有get()方法的功能,除此之外,还会删除get到的元素:

    /*remove()方法的使用*/
        System.out.println("当前共有学生:" + stuList.size() + "名");
        for(int i=stuList.size()-1;i>=0;i--){
            System.out.println("删除学生:" + stuList.remove(i).getName() +  
            ",删除后还剩" + stuList.size() + "名学生");
        }
        /*输出结果为:
        删除学生:linux,删除后还剩2名学生
        删除学生:java,删除后还剩1名学生
        删除学生:python,删除后还剩0名学生
        */

4.3 各种基本数据类型所对应的ArrayList:

        /*
        * 使用包装类,生成各种基本类型数据对应的ArrayList
        * */

        //int和char使用特殊包装类名称
        ArrayList intList = new ArrayList();
        ArrayList charList = new ArrayList();
        //以下均为首字母大写即可
        ArrayList longList = new ArrayList();
        ArrayList shortList = new ArrayList();
        ArrayList floatList = new ArrayList();
        ArrayList doubleList = new ArrayList();
        ArrayList boolList = new ArrayList();
        ArrayList byteList = new ArrayList();

4.4 自动装箱和自动拆箱:

        /*自动装箱*/
        for(int i=0;i

登录查看全部

参与评论

评论留言

还没有评论留言,赶紧来抢楼吧~~

手机查看

返回顶部

给这篇文章打个标签吧~

棒极了 糟糕透顶 好文章 PHP JAVA JS 小程序 Python SEO MySql 确认