引言:
API是什么?
如何使用呢?
Scanner类
Random类
ArrayList类
API API是什么 Application Programming Interface
应用程序编程接口,其实就是一堆前辈已经写好的,可以直接复用的常用组件
API文档的使用 第一看 包路径
第二看 构造方法
第三看 普通方法
引用API的使用步骤
导包
import 包路径. 类名称
如果需要使用的目标类和当前类处于同一个包下,那么就不需要导包了
只有java.lang
包下的内容不需要导包,其他都需要用到import
语句
创建 类名称 对象名 = new 类名称();
使用 对象名.成员方法名()
那么开始学习第一个API吧
Scanner 一个可以使用正则表达式来解析基本类型和字符串的简单文本扫描器。
Scanner 使用分隔符模式将其输入分解为标记,默认情况下该分隔符模式与空白匹配。然后可以使用不同的 next 方法将得到的标记转换为不同类型的值。
包路径:
构造方法: 1 2 3 4 public Scanner (InputStream source)
常用方法: 1 2 3 4 5 6 7 8 public boolean nectInt () public double nectDouble () public float nectFloat () public String nect () public byte nextByte () public short nectShort () public long nectInt () public boolean nextBoolean ()
示例代码: 1 2 3 4 5 6 7 8 9 10 Scanner sc = new Scanner(System.in); int x1 = sc.nextInt();String x2 =sc.next(); long x3 = sc.nextLong();double x4 = sc.nextDouble();byte x5 = sc.nextByte();short x6 = sc.nextShort();boolean x7 = sc.nextBoolean();float x8 = sc.nextFloat();
Random 使用了48位的种子,使用线性同余公式生成伪随机数流
包路径:
构造方法:
常用方法: 1 2 3 4 public int nextInt () public int nextInt (int n)
示例代码: 1 2 3 4 Random r = new Random(); int num = r.nextInt(5 );System.out.println(num); int num2 = r.nextInt(5 )+1 ;
ArrayList List 接口的大小可变数组的实现。
实现了所有可选列表操作,并允许包括 null 在内的所有元素。
除了实现 List接口外,此类还提供一些方法来操作内部用来存储列表的数组的大小
尖括号内的E叫做泛型 ,装在该集合当中的所有元素都必须是统一的类型
泛型只能是引用类型,不能是基本类型
包路径:
构造方法: 1 2 3 public ArrayList (Collection<? extends E> c)
常用方法 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 public E set (int index,E element) ; public E get (int index) public boolean add (E e) public void add (int index,E element) public E remove (int index) public boolean remove (Object o) public void clear () public boolean addAll (Collection<? extends E> c) public boolean addAll (int index,Collection<? extends E> c) public void ensureCapacity (int minCapacity) public boolean isEmpty () public boolean contains (Object o) public int indexOf (Object o) public int lastIndexOf (Object o)
示例代码: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 ArrayList<String> list = new ArrayList<>(); System.out.println(list); list.add("小明" ); list.add(1 ,"小白" ); String str = list.get(0 ); list.set(0 , "小红" ); list.remove(0 ); list.remove("小白" ); list.ensureCapacity(9 ); list.isEmpty(); list.contains("小白" ); list.indexOf("小白" ); list.lastIndexOf("小白" ); ArrayList<String> list2 = new ArrayList<>(); list2.addAll(list); list.size(); for (int i = 0 ; i < list.size(); i++) { System.out.println(list.get(i)); }
泛型只能导入引用类型,那怎么存入基本类型呢?
使用基本类型的对应的包装类
从JDK1.5开始,支持自动装箱拆箱
1 2 3 ArrayList<Integer> list1 = new ArrayList<>(); list1.add(100 ); list1.add(new Integer(100 ));