Java常用类4
Java常用类4
Java比较器
比较对象的大小:使用两个接口的任意一个:Comparable或Comparator
-
Comparable接口的使用
1.像String,包装类等实现了Comparable接口,重写了Compareto()方法,给出比较大小的方式
2.String,包装类重写了Compareto():从小到大排序
3.重写Compareto(obj)的规则:如果当前对象大于形参的obj,返回正整数;反之,返回负整数;相等,返回0
4.自定义类:让自定义类实现Comparable接口,重写Compareto()方法,指明如何排序
String[] arr = new String[]{"AA","CC","ZZ","FF","MM"};
Arrays.sort(arr);
System.out.println(Arrays.toString(arr));
public static void text2(){
//自定义对象排序
Goods[] arr = new Goods[4];
arr[0] =new Goods("lenovoMouse",105);
arr[1] =new Goods("dellMouse",86);
arr[2] =new Goods("xiaomiMouse",66);
arr[3] =new Goods("huaweiMouse",156);
Arrays.sort(arr);
System.out.println(Arrays.toString(arr));
}
//商品类
static class Goods implements Comparable{
String name;
double price;
public Goods(String name,double price){
this.name = name;
this.price = price;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public double getPrice(){
return price;
}
public void setPrice(double price){
this.price = price;
}
@Override
public String toString(){
return "Goods{"+"name='"+name+'\''+",price="+price+'}';
}
//指明比较大小的方法
@Override
public int compareTo(Object o) {
if(o instanceof Goods){
Goods goods = (Goods) o;
if(this.price < goods.price){
return -1;
}else{
return 0;
}
//return Double.compare(this.price,goods.price);
}
throw new RuntimeException("传入的数据类型不一致");
}
}
-
Comparator排序
```java
//定制,Comparator接口
//重写Compare(参数1,参数2)方法,比参数1,2的大小(返回正数:参数1>参数2)
String[] arr = new String[]{"AA","CC","ZZ","FF","MM"};
Arrays.sort(arr,new Comparator(){@Override//字符串从大到小排序 public int compare(Object o1, Object o2) { if(o1 instanceof String&&o2 instanceof String){ String s1 =(String)o1; String s2 =(String)o2; return -s1.compareTo(s2); } throw new RuntimeException("传入的数据类型不一致"); } }); System.out.println(Arrays.toString(arr)); ```
Comparable和Comparator的比较
Comparable:接口一旦确定,保证其实现类的对象在任何位置都能比大小
Comparator:临时的比较
System类
该类的构造器是pivate的,无法创建该类的对象。其内部成员都是static的
Math类
BigInteger与BigDecimal类
BigInteger
可以表示不可变的任意精度的整数
构造器:
BigInteger bigInteger = new BigInteger("12345689");//字符串型
方法
BigDecimal
浮点型,精度比较高(支持任意精度,不可变的有符号的10进制数)
public static void text2(){
BigDecimal bigDecimal = new BigDecimal("12345.123");//被除数
BigDecimal bigDecimal1 = new BigDecimal("11");//除数
System.out.println(bigDecimal.divide(bigDecimal1,BigDecimal.ROUND_HALF_UP));
System.out.println(bigDecimal.divide(bigDecimal1,15,BigDecimal.ROUND_HALF_UP));//15位小数
}