实用类接口
文章目录
枚举
枚举指由一组固定的常量组成的类型
public enum Genders{
Male,Female
}
public class Student{
public Genders sex;
}
Student stu=new Student();
stu.sex=Genders.Male;
stu.sex="你好";//报错
包装类
包装类把基本类型数据转换为对象
每个基本类型在java.lang包中都有一个相应的包装类
包装类的作用
提供了一系列实用的方法
集合不允许存放基本数据类型数据,存放数字时,要用包装类型
包装类的构造方法
所有包装类都可将与之对应的基本数据类型作为参数,来构造它们的实例
//public Type(type value)
Integer i=new Integer(1);
//除Character类外,其他包装类可将一个字符串作为参数构造它们的实例
//public Type(String value)
Integer i=new Integer("123");
注意事项
Boolean类构造方法参数为String类型时,若该字符串内容为true(不考虑大小写),则该Boolean对象表示true,否则表示false
当Number包装类构造方法参数为String 类型时,字符串不能为null,且该字符串必须可解析为相应的基本数据类型的数据,否则编译不通过,运行时会抛出NumberFormatException异常
包装类的常用方法、
XXXValue():包装类转换成基本类型
Integer integerId=new Integer(25);
int intId=integerId.intValue();
toString():以字符串形式返回包装对象表示的基本类型数据(基本类型->字符串)
String sex=Character.toString('男');
String id=Integer.toString(25);
String sex='男'+"";
String id=25+"";
parseXXX():把字符串转换为相应的基本数据类型数据(Character除外)(字符串->基本类型)
int num=Integer.parseInt("36");
boolean bool=Boolean.parseBoolean("false");
valueOf()
所有包装类都有如下方法(基本类型->包装类)
public static Type valueOf(type value)
Integer intValue = Integer.valueOf(21);如:
除Character类外,其他包装类都有如下方法(字符串->包装类)
public static Type valueOf(String s)
Integer intValue = Integer.valueOf("21");
装箱和拆箱
基本类型和包装类的自动转换
Integer intObject = 5;
int intValue = intObject;
//装箱:基本类型转换为包装类的对象
//拆箱:包装类对象转换为基本类型的值
math类
java.lang.Math类提供了常用的数学运算方法和两个静态常量E(自然对数的底数) 和PI(圆周率)
Math.abs(-3.5); //返回3.5
Math.max(2.5, 90.5);//返回90.5
int random = (int) (Math.random() * 10); //生成一个0-9之间的随机数
Random类
Random rand=new Random(); //创建一个Random对象
for(int i=0;i<20;i++){//随机生成20个随机整数,并显示
int num=rand.nextInt(10);//返回下一个伪随机数,整型的 System.out.println("第"+(i+1)+"个随机数是:"+num);
}
String类
length()方法
String类提供了length()方法,确定字符串的长度
equals()方法
String类提供了equals( )方法,比较存储在两个字符串对象的内容是否一致
equals():检查组成字符串内容的字符是否完全一致
==和equals()有什么区别呢:==判断两个字符串在内存中的地址,即判断是否是同一个字符串对象
字符串比较的其他方法
使用equalsIgnoreCase()忽略大小写
使用toLowerCase()小写
使用toUpperCase()大写
字符串连接
方法1:使用“+”
方法2:使用String类的concat()方法
其他方法**
使用equalsIgnoreCase()忽略大小写
使用toLowerCase()小写
使用toUpperCase()大写
字符串连接
方法1:使用“+”
方法2:使用String类的concat()方法


被折叠的 条评论
为什么被折叠?



