Java—工具类使用

条件判断

@NoArgsConstructor(access = AccessLevel.PRIVATE)
​
// Object对象判断
// 不推荐使用 hutool 的,因为 jdk 不能自动识别,会产生异味
import cn.hutool.core.util.ObjectUtil;
ObjectUtil.isNotNull
// 推荐使用 java.util 提供的工具类
Objects.nonNull
​
​
​
// String对象判断
// 不推荐使用 hutool 的,因为 jdk 不能自动识别,会产生异味
import cn.hutool.core.util.StrUtil;
StrUtil.isNotBlank
// 推荐使用 apache 的
import org.apache.commons.lang3.StringUtils;
StringUtils.isNotBlank
// google guava
import com.google.common.base.Strings;
Strings.isNullOrEmpty(name);
​
// Collection对象判断
// 不推荐使用 hutool 的,因为 jdk 不能自动识别,会产生异味
import cn.hutool.core.collection.CollectionUtil;
CollectionUtil.isNotEmpty
// 推荐使用 apache 的
import org.apache.commons.collections.CollectionUtils;
CollectionUtils.isNotEmpty
​
​
​
// equals判断
Objects.equals()
StringUtils.equals()

# 对象拷贝

BeanConverter

这个是 idea 的一个插件,可以帮你生成一个 Convert类。

Mapstruct

官网:MapStruct – Java bean mappings, the easy way!

学习文档:MapStruct 1.5.5.Final Reference Guide

学习代码:mapstruct-examples/mapstruct-clone/src/main/java/org/mapstruct/example/dto/CustomerDto.java at main · mapstruct/mapstruct-examples · GitHub

简介

  • 不同类型之间可以相互转换,但是如果 String 转 Integer,你的值是 "aa",那就会报类型转换异常

  • 不同名字可以通过 @Mapping(source = "tel", target = "telNumber") 做映射

  • 可以设置默认值 @Mapping(source = "tel", target = "telNumber", defaultValue = "我的默认值"),

  • @Mapping(target = "creationDate", expression = "java(new java.util.Date())")

  • 也可以给目标设置常量,@Mapping(target = "telNumber", constant = "我的常量"),不可有 source,

  • 其他数据类型也可以正常转换,比如 List,

  • 格式转换,@Mapping(source = "price", target = "price", numberFormat = "0.00"),目前只发现转换成 String 的时候可以成功,

  • 日期格式转换也是,只有转成 String 才会成功 @Mapping(source = "birthday", target = "birthday", dateFormat = "yyyy-MM-dd HH:mm:ss")。

  • 把 A 的属性赋值给 B,如果 B 本来就有值,会覆盖掉

  • 忽略 @Mapping(target = "modificationTime", ignore = true)

  • source 的空值 "" 和 null 也会赋值给 target,

  • 在类上加上 @Mapper(nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE, nullValueCheckStrategy = NullValueCheckStrategy.ALWAYS),可以忽略 null,

  • list to string:@Mapping(target = "list", expression = "java(com.alibaba.fastjson.JSON.toJSONString(user.getList()))"),

  • List 的转换是建立在单个的基础之上的,即 @Mappings 写在单个上,List 只是去调用单个的映射方式。

@Mapper(nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE,
    nullValueCheckStrategy = NullValueCheckStrategy.ALWAYS)
public interface ShopInfoConvert {
    /**
     * Is not empty boolean.
     *
     * @param value the value
     * @return the boolean
     */
    @Condition
    static boolean isNotEmpty(String value) {
        return StringUtils.isNotBlank(value);
    }
    /**
     * To do.
     *
     * @param entity  the entity
     * @param request the request
     */
    @Mappings({
        @Mapping(target = "createBy", expression = "java(UserDetailUtil.getUserId())"),
        @Mapping(target = "createDate", expression = "java(new java.util.Date())"),
//        @Mapping(target = "updateBy", expression = "java(UserDetailUtil.getUserId())"),
        @Mapping(target = "updateDate", expression = "java(new java.util.Date())"),
    })
    void toDo(@MappingTarget MallShopInfo entity, SaveRequest request);
}

多源映射

@Mapper
public interface AddressMapper {
    @Mapping(target = "description", source = "person.description")
    @Mapping(target = "houseNumber", source = "address.houseNo")
    DeliveryAddressDto personAndAddressToDeliveryAddressDto(Person person, Address address);
}

源参直接映射

可以把参数列表中的参数值直接做映射。

@Mapper
public interface AddressMapper {
    @Mapping(target = "description", source = "person.description")
    @Mapping(target = "houseNumber", source = "hn")
    AddressDto personAddressDto(Person person, Integer hn);
}

用 . 指代同名参数

生成的代码可以直接地映射每个属性从 CustomerDto.record 给 Customer不需. The same goes for Customer.account.

@Mapper
public interface CustomerMapper {
  @Mapping( target = "name", source = "record.name" )
  @Mapping( target = ".", source = "record" )
  @Mapping( target = ".", source = "account" )
  Customer customerDtoToCustomer(CustomerDto customerDto);
} 

子类映射

如果Fruit是抽象类或接口,则会出现编译错误。

@Mapper
public interface FruitMapper {
  @SubclassMapping( source = AppleDto.class, target = Apple.class )
  @SubclassMapping( source = BananaDto.class, target = Banana.class )
  Fruit map( FruitDto source );
}

String 不为 null 且不为空时转换

@Condition
default boolean isNotEmpty(String value) {
    return StringUtils.isNotBlank(value);
}

不同服务模块都需要加上插件

假如你定义了一个父转换器在 A模块,然后依赖和插件都放在 A模块里面了;现在定义了一个子转换器在 B模块,那么也需要假如此插件,否则不会生成实现类。

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.0</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
                <annotationProcessorPaths>
                    <path>
                        <groupId>org.projectlombok</groupId>
                        <artifactId>lombok</artifactId>
                        <version>${lombok.version}</version>
                    </path>
                    <path>
                        <groupId>org.mapstruct</groupId>
                        <artifactId>mapstruct-processor</artifactId>
                        <version>${mapstruct.version}</version>
                    </path>
                </annotationProcessorPaths>
                <compilerArgs>
                    <compilerArg>-Amapstruct.defaultComponentModel=spring</compilerArg>
                    <compilerArg>-Amapstruct.suppressGeneratorTimestamp=true</compilerArg>
                    <compilerArg>-Amapstruct.suppressGeneratorVersionInfoComment=true</compilerArg>
                </compilerArgs>
            </configuration>
        </plugin>
    </plugins>
</build>

映射 List 时的注意点

  • List 的转换是建立在单个的基础上的。

  • List 的转换建立在单个的基础上,若这个单个需要自定义,那么必须使用 A toA(B b); 这种;不可使用 toA(@MappingTarget A a, B b); 这种形式,否则 mapstruct 会自动帮你建立一个默认的 A toA(B b);实现。

@Mappings({
    @Mapping(target = "fansAddressId", source = "id"),
    @Mapping(target = "provinceId", source = "provinceNo"),
    @Mapping(target = "cityId", source = "cityNo"),
    @Mapping(target = "districtId", source = "areaNo"),
    @Mapping(target = "district", source = "area"),
    @Mapping(target = "mobile", source = "phone"),
})
UserAddressVO toVo(RnUserAddressVO rnAddress);
​
void toVo(@MappingTarget List<UserAddressVO> voList, List<RnUserAddressVO> rnAddressList);

实践1

依赖

<properties>
  <mapstruct.version>1.5.2.Final</mapstruct.version>
  <lombok.version>1.16.22</lombok.version>
</properties>
​
<dependencies>
  <dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>${lombok.version}</version>
  </dependency>
  <dependency>
    <groupId>org.mapstruct</groupId>
    <artifactId>mapstruct</artifactId>
    <version>${mapstruct.version}</version>
  </dependency>
</dependencies>
​
<build>
  <plugins>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-compiler-plugin</artifactId>
      <version>3.8.1</version>
      <configuration>
        <source>1.8</source>
        <target>1.8</target>
        <annotationProcessorPaths>
          <path>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>${lombok.version}</version>
          </path>
          <path>
            <groupId>org.mapstruct</groupId>
            <artifactId>mapstruct-processor</artifactId>
            <version>${mapstruct.version}</version>
          </path>
        </annotationProcessorPaths>
        <compilerArgs>
          <compilerArg>-Amapstruct.defaultComponentModel=spring</compilerArg>
          <compilerArg>-Amapstruct.suppressGeneratorTimestamp=true</compilerArg>
          <compilerArg>-Amapstruct.suppressGeneratorVersionInfoComment=true</compilerArg>
        </compilerArgs>
      </configuration>
    </plugin>
  </plugins>
</build>

对象类

getter、setter。

public class User {
    private Integer id ;
    private String userName;
    private Date birthday;
    String tel;
}
​
public class UserVo {
    private String id;
    private String userName;
    /**
     * 类型不同
     */
    private Date birthday;
    private String telNumber;
}

转换mapper

import com.chw.pojo.User;
import com.chw.pojo.UserVo;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Mappings;
import org.mapstruct.factory.Mappers;
​
// 将转换器注入到ioc容器
@Mapper
// @Mapper(componentModel = "spring")
public interface UserMapper {
    UserMapper INSTANCE = Mappers.getMapper(UserMapper.class);
    @Mappings({
        @Mapping(source = "tel", target = "telNumber"),
        @Mapping(source = "birthday", target = "birthday", dateFormat = "yyyy-MM-dd")
    })
    UserVo convertToVo(User user);
    
    @Mappings({
      @Mapping(source = "tel", target = "telNumber"),
      @Mapping(source = "birthday", target = "birthday", dateFormat = "yyyy-MM-dd HH:mm")
    })
    void mapper1(User user, @MappingTarget UserVo userVo);
}

测试

@Resource
private UserMapper userMapper;
@Test
public void userToUserVO() {
    User user = new User(1, "aa", new DateTime(), "123456");
    UserVo userVo = userMapper.convertToVo(user);
    // 或者 UserMapper.INSTANCE.convertToVo(user);
    System.out.println(userVo);
}

实践2 - qualifier

import com.chw.pojo.User;
import com.chw.pojo.UserVo;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import org.apache.commons.lang3.StringUtils;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.MappingTarget;
import org.mapstruct.Mappings;
import org.mapstruct.NullValueCheckStrategy;
import org.mapstruct.NullValuePropertyMappingStrategy;
import org.mapstruct.Qualifier;
@Mapper(nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE, nullValueCheckStrategy = NullValueCheckStrategy.ALWAYS)
public interface UserMapper {
    @Mappings({
        @Mapping(source = "tel", target = "telNumber"),
        @Mapping(source = "birthday", target = "birthday", dateFormat = "yyyy-MM-dd HH:mm")
    })
    UserVo convertToVo(User user);
    
    @Mappings({
        @Mapping(source = "tel", target = "telNumber", defaultValue = "我的默认值"),
        @Mapping(source = "price", target = "price", numberFormat = "0.00"),
        @Mapping(source = "birthday", target = "birthday", dateFormat = "yyyy-MM-dd"),
        @Mapping(target = "userName", qualifiedBy = EmptyStringToNull.class)
    })
    void mapper1(User user, @MappingTarget UserVo userVo);
    
    @Qualifier
    @java.lang.annotation.Target(ElementType.METHOD)
    @Retention(RetentionPolicy.CLASS)
    @interface EmptyStringToNull {
    }
    @EmptyStringToNull
    default String emptyStringToNull(String s) {
        return StringUtils.isNotBlank(s) ? s : null;
    }
}

实践3 - 父类继承

// 父类。父类定义了 isNotEmpty,那么子类都能用上
public interface BaseConvert<D, E> {
​
    E toEntity(D dto);
​
    D toDto(E entity);
​
    List<E> toEntity(List<D> dtoList);
​
    List<D> toDto(List<E> entityList);
​
    @Condition
    static boolean isNotEmpty(String value) {
        return StringUtils.isNotBlank(value);
    }
}
​
// 子类
@Mapper(nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE,
    nullValueCheckStrategy = NullValueCheckStrategy.ALWAYS)
public interface VipInfoConvert extends BaseConvert<VipInfo, WscVipInfo> {
​
    void toWscVipInfo(VipInfo vipInfo, @MappingTarget WscVipInfo wscVipInfo);
​
    void toVipInfo(WscVipInfo wscVipInfo, @MappingTarget VipInfo vipInfo);
​
    @Mappings({@Mapping(target = "userId", ignore = true),
        @Mapping(source = "userId", target = "custNo"), @Mapping(source = "mobilePhone", target = "mobile"),
        @Mapping(source = "shopStoreName", target = "nickName"), @Mapping(source = "channelCode", target = "orgType"),
        @Mapping(source = "otOpenid", target = "thirdOpenId"), @Mapping(source = "uniqueNo", target = "thirdCustNo")})
    void toVipInfo(VipLoginData vipLoginData, @MappingTarget VipInfo vipInfo);
​
    @Mappings({@Mapping(target = "userId", ignore = true),
        @Mapping(source = "wscVipInfo.familyNo", target = "familyNo"),
        @Mapping(source = "vipLoginData.userId", target = "custNo"),
        @Mapping(source = "vipLoginData.mobilePhone", target = "mobile"),
        @Mapping(source = "vipLoginData.shopStoreName", target = "nickName"),
        @Mapping(source = "vipLoginData.shopNo", target = "shopNo"),
        @Mapping(source = "vipLoginData.merchantCode", target = "merchantCode"),
        @Mapping(source = "vipLoginData.shopStoreCode", target = "shopStoreCode"),
        @Mapping(source = "vipLoginData.channelCode", target = "orgType"),
        @Mapping(source = "vipLoginData.vipIdCard", target = "vipIdcard"),
        @Mapping(source = "vipLoginData.sex", target = "sex"),
        @Mapping(source = "vipLoginData.trueName", target = "trueName"),
        @Mapping(source = "vipLoginData.otOpenid", target = "thirdOpenId"),
        @Mapping(source = "vipLoginData.uniqueNo", target = "thirdCustNo")})
    void toVipInfo(@MappingTarget VipInfo vipInfo, WscVipInfo wscVipInfo, VipLoginData vipLoginData);
}

数值计算

代码review

https://www.cnblogs.com/candlia/p/11920108.html

其他工具

非自主抛异常

@SneakyThrows

@SneakyThrows注解-CSDN博客

普通Exception类,也就是我们常说的受检异常或者Checked Exception会强制要求抛出它的方法声明throws,调用者必须显示的去处理这个异常。设计的目的是为了提醒开发者处理一些场景中必然可能存在的异常情况。比如网络异常造成IOException。

但是现实大部分情况下的异常,我们都是一路往外抛了事。所以渐渐的java程序员处理Exception的常见手段就是外面包一层RuntimeException,接着往上丢

而Lombok的@SneakyThrows就是为了消除这样的模板代码。

使用注解后不需要担心Exception的处理

非空判断取值

sysTagInfo.setShopNo(Optional.ofNullable(shopNo)
    .filter(item -> StringUtils.isNotBlank(item.trim()))
   .map(String::trim).orElse(getShopNo()));

入参出参序列化工具

当需要对入参出参做动作时,一定要想到序列化工具,因为你自己去判断对象内的值是否有 null 是一件很麻烦的事情,那么你就要想到,我对象传给前端变成 json字符串的时候,是怎么样一个过程,类似于 jackson 这种工具能不能帮我们自动完成 null 的去除呢。

jackson

一般入参出参都是用的 json字符串来转换的,jackson 是一个很强大的自动转换工具。

出参序列化忽略null

当你传给前端的对象中有空值时,前端拿到然后显示的就会是 null,这是很不美观的。那么我们就可以让 Jackson 在将对象序列化为 json字符串的时候忽略 null。

// bootstrap.properties  中加上
spring.jackson.default-property-inclusion=non_null
​
// 或者对指定属性加上注解
@JsonInclude(JsonInclude.Include.NON_NULL)

hutool工具类

中文文档:Hutool参考文档

<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.8.5</version>
</dependency>

克隆

JDK 中的 Cloneable接口只是一个空接口,并没有定义成员,它存在的意义仅仅是指明一个类的实例化对象支持位复制(就是对象克隆),如果不实现这个类,调用对象的 clone()方法就会抛出 CloneNotSupportedException异常。并且因为 clone()方法在 Object对象中,所以返回值也是 Object对象,因此克隆后我们需要自己强转下类型。

实现接口重写克隆方法

优点就是 Java 可以多实现,所以不会有限制;缺点就是需要自己重写,还要自己处理异常。

private static class Cat implements Cloneable<Cat>{
    @Override
    public Cat clone() {
        try {
            return (Cat) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new CloneRuntimeException(e);
        }
    }
}

继承父类直接可以克隆

优点就是不需要自己重写了,缺点就是 Java 不能多继承。

private static class Dog extends CloneSupport<Dog>{ // ... }

深克隆

以下三种方法都可进行深克隆。

ObjectUtil.clone(obj);
ObjectUtil.cloneByStream(obj);
ObjectUtil.cloneIfPossible(obj);

URL编码解码

URLEncoder.encode(encrypt, StandardCharsets.UTF_8.name());

SESSION学习

// 会获取这个 request 中的 session,如果为空则会为此 request 创建新 session
// 所以推荐使用 request.getSession(false),然后记得做非空判断,他不会自动创建
request.getSession()
​

Google guava 工具类

简介

Guava 是对 JavaAPI 的补充,

2.1-不可变集合 | Google Guava 中文教程

实践1

依赖

<guava.version>31.0.1-jre</guava.version>
​
<!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>${guava.version}</version>
</dependency>

使用

Strings

import com.google.common.base.Strings;
​
// 如果值为 null,则转成 ""
String entity = Strings.nullToEmpty(name);
​
// 判断是否为 null或空字符串
Strings.isNullOrEmpty(name);

新集合工具类

不可变集合 ImmutableList
  • 当对象被不可信的库调用时,不可变形式是安全的;

  • 不可变对象被多个线程调用时,不存在竞态条件问题

  • 不可变集合不需要考虑变化,因此可以节省时间和空间。所有不可变的集合都比它们的可变形式有更好的内存利用率(分析和测试细节);

  • 不可变对象因为有固定不变,可以作为常量来安全使用。

ImmutableList<String> iList = ImmutableList.of("a", "b", "c");
Lists
List<Integer> list1 = Lists.newArrayList(1, 2, 3, 4, 5);
// 根据长度分区
List<List<Integer>> partition = Lists.partition(list1, 2);

key可重复Map

// 这个 Multimap,重复的
Multimap<String,Integer> mapM = ArrayListMultimap.create();
mapM.put("test",1);
mapM.put("test",2);
​

交集、并集、差集

Set 的
Set<Integer> set1 = Sets.newHashSet(1, 3, 5, 7, 9);
Set<Integer> set2 = Sets.newHashSet(5, 7, 9, 6, 8, 10);
// 交集
SetView<Integer> setIntersection = Sets.intersection(set1, set2);
setIntersection.forEach(System.out::println);
// 并集
SetView<Integer> setUnion = Sets.union(set1, set2);
setUnion.forEach(System.out::println);
// 差集
SetView<Integer> setDifference = Sets.difference(set1, set2);
setDifference.forEach(System.out::println);
// 双方的差集的和
SetView<Integer> symmetricDifference = Sets.symmetricDifference(set1, set2);
​
// 实践
HashSet<Long> oldDictDataNoSet = oldDataList.stream().map(ShopChannelData::getDictDataNo).distinct().collect(Collectors.toCollection(Sets::newHashSet));
HashSet<Long> newDictDataNoSet = Sets.newHashSet(newDictDataNoList);
SetView<Long> deleteDictDataNoSet = Sets.difference(oldDictDataNoSet, newDictDataNoSet);
SetView<Long> insertDictDataNoSet = Sets.difference(newDictDataNoSet, oldDictDataNoSet);

Map 的

MapDifference 这个对象内就有了交集、差集

Map<Integer, Integer> map1 = Maps.newHashMap();
map1.put(1,1);
map1.put(2,2);
Map<Integer, Integer> map2 = Maps.newHashMap();
map2.put(2,2);
map2.put(3,3);
​
MapDifference<Integer, Integer> mapDifference = Maps.difference(map1, map2);

List 通过 Set 来实现
List<Integer> list1 = Lists.newArrayList(1, 2, 3, 4, 5);
List<Integer> list2 = Lists.newArrayList(3, 4, 5, 6, 7, 8);
SetView<Integer> intersection = null;
// 如果 list1 为空会报错,所以需要做判断
if (CollectionUtils.isNotEmpty(list1) && CollectionUtils.isNotEmpty(list2)) {
    intersection = Sets.intersection(Sets.newHashSet(list1), Sets.newHashSet(list2));
}
List<Integer> intersectionList = Lists.newArrayList(intersection);

缓存 LoadingCache

3-缓存 | Google Guava 中文教程

类型转换

我们常用的类型转换就是得到 String,然后进行解析转换成对象,但是需要加上 try/catch 来预防转换失败。

Hutool 可以实现自定义类型转换,具体类型

Convert类

此类的大部分方法为 toXXX,参数1 为 Object,参数2 为 defaultValue,转换失败时返回这个默认值。

这个类的方法特别多,具体使用到或想去使用的时候可以搜一下。

// Object对象转换成 String
Convert.toStr
​
// Object对象转换成 Integer数组
Convert.toIntArray
​
// Object对象转换成 Date对象
Convert.toDate
​
// 半角转全角
Convert.toSBC
// 全角转半角
Convert.toDBC

泛型类型转换

通过 convert(TypeReference<T> reference, Object value)方法,自行 new 一个TypeReference对象,可以对嵌套泛型进行类型转换。

// 例如我们想转换一个对象为 List<String>类型
Object[] obj = {"你", "好", "", 1};
List<String> list 
      = Convert.convert(new TypeReference<List<String>>() {}, obj);

JSON处理

// JSON字符串转换成 List
// import cn.hutool.json.JSONUtil;
JSONUtil.toList(redisResult, MobileCategoryVo.class);

日期时间

各工具类

  • DateUtil 针对日期时间操作提供一系列静态方法

  • DateTime 提供类似于 Joda-Time 中日期时间对象的封装,继承自 Date类,并提供更加丰富的对象方法。

  • DatePattern 提供常用的日期格式化模式,包括 String类型和 FastDateFormat两种类型。

  • DateUnit,时间枚举工具类,可以枚举很多时间。

  • FastDateFormat 提供线程安全的针对Date对象的格式化和日期字符串解析支持。此对象在实际使用中并不需要感知,相关操作已经封装在DateUtil和DateTime的相关方法中。

  • DateBetween 计算两个时间间隔的类,除了通过构造新对象使用外,相关操作也已封装在DateUtil和DateTime的相关方法中。

  • TimeInterval 一个简单的计时器类,常用于计算某段代码的执行时间,提供包括毫秒、秒、分、时、天、周等各种单位的花费时长计算,对象的静态构造已封装在DateUtil中。 Splitter 和 Joinner

  • 9
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1. Java工具概述 很多人初学程序时,总是在想,那么多的算法该怎么写呀?那么多的数据结构都不熟悉,该怎么实现呀?总是担心英语不好程序学不精通,数学不好写程序无法达到巅峰。学的程序越多,不懂的知识越多。 这种想法很正常,毕竟传统的计算机教育都是从原理开始的,科学原理一般理解起来还能够接受,但是实现起来都很难。计算机发展到了今天,能成为原理的基本已经有人实现了,今天我们学习任何知识都是站在巨人的肩膀上,只要理解程序运行原理,算法的功能即可。底层的各种算法,各种数据结构已经被“巨人们”实现了,一般都放在程序开发类库中,程序员开发过程中直接调用即可。 比如现在木工做家具,已经不存在自己砍树、加工木板、一点一点的雕刻了,如果需要木板,直接到市场上购买,需要各种图案,直接到市场购买,木工的工作就是把这些木板修理一下组装成一套家具即可。“工欲善其事,必先利其器”,在Java程序开发过程中,很多算法(比如:MD5加密算法)、很多数据结构(比如链表LinkedList)已经实现并且大多放在类库的java.util包中,程序员只需要了解各种工具的功能就可以直接调用。比如对一个数组进行排序,程序员可以写如下排序算法: 代码演示:数组排序 public static void sort(int[] arrs) { boolean isSwap = false; for (int i = 0; i < arrs.length - 1; i++) { isSwap = false; for (int j = arrs.length - 1; j > i; j--) { if (arrs[j - 1] > arrs[j]) { isSwap = true; int tmp = arrs[j - 1]; arrs[j - 1] = arrs[j]; arrs[j] = tmp; } } } } 该排序算法中只能对整数数组排序,还有其他数据类型呢?就需要重载很多方法进行排序操作。而在Java类库中有一个Arrays类的sort方法已经实现各种数据类型的排序算法。程序员只需要调用该类的方法即可。 代码演示:Arrays实现排序 public static void main(String[] args) { int[] ages={23, 45,12,76,34,56,24}; Arrays.sort(ages); for (int i = 0; i < ages.length; i++) { System.out.println(ages[i]); } } 在Java开发类库中,提供了很多工具类,我们即将学习最常见的工具类,比如对日期的操作,对集合的操作等。具体更多的工具类,请参考JavaDoc文档。 2. java.util.Date类 Date类包装了毫秒值,毫秒值表示自1970年1月1日00:00:00 GMT开始到现在经过的毫秒数。该类的大部分构造器和方法都已经过时,但是该类使用非常方便,因此目前使用还很普遍,该类的另一个主要功能是,在数据库操作中,它允许将毫秒值表示为SQL DATE值,是数据库操作中java.sql.Date的父类。关于数据库操作,将在第八章开始讲解。 该类目前推荐使用的构造方法有两个: 构造方法 说明 Date() 按照当前系统时间构造一个Date对象。 Date(long date) 按照给定的时间毫秒值构造一个 Date 对象。 表1 java.util.Date类的构造方法 主要的方法有: 返回 异常 说明 boolean after(Date when) 测试当前对象表示的时间是否在指定时间之后。 boolean before(Date when) 测试当前对象表示的时间是否在指定时间之前。 long getTime() 返回当前对象对应的时间毫秒值 void setTime(long time) 设置时间 表2 java.util.Date类的主要方法 代码演示:时间设置 public class Demo2 { public static void main(String[] args) { Date date=new Date(); ① date.setTime((10L*365+2)*24*60*60*1000); ② System.out.println(date); ③ } } 代码解析: ① 构造当前系统时间。 ② 设置时间值为1970年后10年的时间的毫秒值,10年间有2个闰年,10年的天数是:10*365+2,10L表示当前值是long类型。 ③ 调用Date的toString方法输出结果。 代码输出结果: Tue Jan 01 08:00:00 CST 1980 Q 老师,时间毫秒值从1970年1月1日0:00.000开始计算,上面示例中10年后应该是1980年1月1日0:00.000,为什么输出结果是:1980年1月1日 8:00呢? A java.util.Date类型表示的是GMT时间,本身输出是国际化输出,由于中国处于东八区时间,因此输出结果是早上8点。而Date的其他构造方法和普通方法的API都不容易实现国际化,因此目前Date类的大多数方法都被标识为过时,表示更灵活的时间类请参考java.util.Calendar。 Date的输出结果是按照国际通用格式输出的,而中国更习惯于“年-月-日”的形式输出,这种特殊格式的输出需要用到Java格式化工具。 3. 格式化工具 格式化的目的是把一个对象以不同的格式表示,以满足不同环境对格式的要求,比如:前面学习的Date对象实质是一个以毫秒值表示的时间,但是在不同的国家和地区表示方式不一样。那么就需要对Date进行格式化处理。接下来主要学习Java对日期时间的格式化和对数字的格式化处理。  日期时间格式化 Date类中包含了日期和时间,在Java编程中,日期通常指年、月、日,时间则指时、分、秒、毫秒。Java对Date进行格式化使用java.text.DateFormat类。在格式表示中,经常采用4种格式,这四种格式被定义为DateFormat类的常量。下表所示: 格式 说明 SHORT 以最短的格式表示,比如:09-8-20 MEDIUM 比short完整表示方式,比如:2009-8-20 LONG 比medium更完整的表示方式,比如:2009年8月20日 FULL 综合的表示方式,比如:2009年8月20日 星期四 表3 DateFormat的四种表示格式 因为不同国家地区需要格式化的结果不同,Locale类的对象表示了不同的区域,Locale定义目前全世界几乎所有地区的对象表示,比如: 格式 说明 Locale.CHINA 中国地区 Locale.US 美国地区 Locale.FRANCE 法国地区 Locale.CANADA 加拿大地区 表4 Locale对部分地区的表示 DateFormat是一个抽象类,不能直接实例化,可以使用下表中的静态方法得到DateFormat的对象。 方法 说明 getDateInstance() 返回默认地区,默认格式的关于日期的DateFormat对象。 getDateInstance(int) 返回指定格式下,默认地区的关于日期的DateFormat对象。 getDateInstance(int, Locale) 返回指定格式,指定地区的关于日期的DateFormat对象。 getTimeInstance() 返回默认地区,默认格式的关于时间的DateFormat对象。 getTimeInstance (int) 返回默认地区,指定格式的关于时间的DateFormat对象。 getTimeInstance (int, Locale) 返回指定地区,指定格式的关于时间的DateFormat对象。 getDateTimeInstance() 返回默认地区、默认日期格式、默认时间格式的关于日期和时间的DateFormat对象。 getDateTimeInstance (int,int) 返回默认地区、指定日期格式、指定时间格式的关于日期和时间的DateFormat对象。 getDateTimeInstance (int,int, Locale) 返回指定地区、指定日期格式、指定时间格式的关于日期和时间的DateFormat对象。 表5 获取DateFormat对象的静态方法 调用DateFormat对象的format方法可以把Date对象转换成为指定格式的String类型数据。比如: Date today=new Date(); DateFormat df=DateFormat.getDateInstance(DateFormat.FULL,Locale.CHINA); String result=df.format(today); 代码演示:日期的不同格式 import java.text.DateFormat; import java.util.Date; import java.util.Locale; public class Demo3 { public static void main(String[] args) { Date today = new Date(); Locale[] locals = new Locale[] { Locale.CHINA, Locale.US, Locale.UK }; for (int i = 0; i < locals.length; i++) { DateFormat df1 = DateFormat.getDateInstance(DateFormat.SHORT, locals[i]); DateFormat df2 = DateFormat.getDateInstance(DateFormat.MEDIUM, locals[i]); DateFormat df3 = DateFormat.getDateInstance(DateFormat.LONG, locals[i]); DateFormat df4 = DateFormat.getDateInstance(DateFormat.FULL, locals[i]); System.out.println(locals[i].getDisplayCountry() + "的日期形式:"); System.out.println("\tShort格式:" + df1.format(today)); System.out.println("\tMedium格式:" + df2.format(today)); System.out.println("\tLong格式:" + df3.format(today)); System.out.println("\tFull格式:" + df4.format(today)); } } } 代码输出结果: 中国的日期形式: Short格式:09-8-20 Medium格式:2009-8-20 Long格式:2009年8月20日 Full格式:2009年8月20日 星期四 美国的日期形式: Short格式:8/20/09 Medium格式:Aug 20, 2009 Long格式:August 20, 2009 Full格式:Thursday, August 20, 2009 英国的日期形式: Short格式:20/08/09 Medium格式:20-Aug-2009 Long格式:20 August 2009 Full格式:20 August 2009 在Java程序设计过程中,对应日期和时间的格式化,还有一个简单的格式化方式,就是java.text.SimpleDateFormat,该类中用字符串指定日期和时间的格式,字符串中的字符称为模式字符,模式字符区分大小写。常见的模式字符定义如下: 字母 日期或时间元素 y 年 M 年中的月份 w 年中的周数 W 月份中的周数 D 年中的天数 d 月份中的天数 F 月份中的星期 E 星期中的天数 a Am/pm 标记 H 一天中的小时数(0-23) k 一天中的小时数(1-24) K am/pm 中的小时数(0-11) h am/pm 中的小时数(1-12) m 小时中的分钟数 s 分钟中的秒数 S 毫秒数 表6 模式字符串 例如: 日期和时间模式 结果 "EEE, MMM d, ''yy" Wed, Jul 4, '01 "h:mm a" 12:08 PM "yyyy-MM-dd HH:mm:ss" 2009-8-20 14:22 "yyyy年MM月dd HH:mm:ss" 2009年8月20 14:22:23 表7 模式字符串示例 SimpleDateFormat是DateFormat的子类,用法和DateFormat类基本一致,主要使用format()方法。 代码演示:SimpleDateFormat进行日期转换 import java.text.SimpleDateFormat; import java.util.Date; public class Demo4 { public static void main(String[] args) { Date today = new Date(); SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat format2 = new SimpleDateFormat("yyyy年MM月dd HH:mm:ss"); SimpleDateFormat format3 = new SimpleDateFormat("HH:mm:ss"); SimpleDateFormat format4 = new SimpleDateFormat("yyyy"); System.out.println(format1.format(today)); System.out.println(format2.format(today)); System.out.println(format3.format(today)); System.out.println(format4.format(today)); } } 代码输出结果: 2009-08-20 2009年08月20 14:25:58 14:25:58 2009 在程序设计时,界面上用户输入的基本上都是字符串,如果字符串输入一个出生年月,如何把该字符串转换成Date类型呢?可以使用SimpleDateFormat的parse()方法。 代码演示:SimpleDateFormat解析日期 import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class Demo5 { public static void main(String[] args) { String birthday="1980-04-16"; SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd"); try { Date bir=format.parse(birthday); System.out.println(bir); } catch (ParseException e) { ① // TODO Auto-generated catch block e.printStackTrace(); } } } 代码解析: ① 用SimpleDateFormat解析日期的时候需要处理其中的ParseException异常。  数字格式化 对数字的格式化,在程序处理中也是非常常用的,数字格式化主要对小数点位数,表示的形式(比如:百分数表示)等格式处理。 NumberFormat 是所有数值格式的抽象基类。此类提供格式化和解析数值的接口。若要格式化当前Locale的数值,可使用其中一个方法: myString = NumberFormat.getInstance().format(myNumber); 若要格式化不同 Locale 的日期,可在调用getInstance方法时指定它。 NumberFormat nf = NumberFormat.getInstance(Locale.FRENCH); 方法 说明 getInstance() 获取常规数值格式。可以指定Local参数。 getNumberInstance() 获取常规数值格式。可以指定Local参数。 getIntegerInstance() 获取整数数值格式。可以指定Local参数。 getCurrencyInstance () 获取货币数值格式。可以指定Local参数。格式化后的数据前面会有一个货币符号,比如:“¥” getPercentInstance() 获取显示百分比的格式。可以指定Local参数。比如:小数 0.53 将显示为 53%。 表8 获取NumberFormat对象 代码演示:NumberFormat进行数字格式化 import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.Locale; public class Demo6 { public static void main(String[] args) { double mynum1 = 230456789; double mynum2 = 0.23; NumberFormat nf1 = NumberFormat.getInstance(Locale.CHINA); NumberFormat nf2 = NumberFormat.getCurrencyInstance(Locale.CHINA); NumberFormat nf3 = NumberFormat.getCurrencyInstance(Locale.US); NumberFormat nf4 = NumberFormat.getPercentInstance(); System.out.println(nf1.format(mynum1)); System.out.println(nf2.format(mynum1)); System.out.println(nf3.format(mynum1)); System.out.println(nf4.format(mynum2)); } } 代码输出结果: 230,456,789 ¥230,456,789.00 $230,456,789.00 23% 关于更复杂的数字格式化,可以使用java.text.DecimalFormat进行处理,该类通过模式字符串对数字格式化。 代码演示:DecimalFormat进行数字格式化 import java.text.DecimalFormat; public class Demo7 { public static void main(String[] args) { int num1=1234567; double num2=0.126543; DecimalFormat df1=new DecimalFormat("#,###"); ① DecimalFormat df2=new DecimalFormat("#.00"); ② DecimalFormat df3=new DecimalFormat("00.#"); ③ DecimalFormat df4=new DecimalFormat("0.##E0"); ④ DecimalFormat df5=new DecimalFormat("0.##%"); ⑤ System.out.println(df1.format(num1)); System.out.println(df2.format(num2)); System.out.println(df3.format(num2)); System.out.println(df4.format(num1)); System.out.println(df5.format(num2)); } } 代码解析: ① #:代表一个位置数字,如果该位置数字不存在,则省略不显示。 ,:代表数字中的分隔符,此示例用三位分隔一次。 ② 0:代表一个数字位置,如果该位置不存在,则用0来补充。小数中多余部分四舍五入。 .:表示小数点。 #:当前位置是0,则省略不显示。 ③ #:小数部分只显示1位小数,并且进行四舍五入。 ④ E:科学计数法。 ⑤ %:用百分数表示数字。 代码输出结果: 1,234,567 .13 00.1 1.23E6 12.65% 4. java.util.Calendar Calendar类是一个抽象类,它为特定的值诸如YEAR、MONTH、DAY_OF_MONTH、HOUR等日历字段之间的转换和操作日历字段(例如获得下星期的日期)提供了丰富的方法。并且可以非常方便的与Date类型进行相互转换。 使用静态方法getInstance()和getInstance(Locale locale)获取Calendar对象。Calendar定义了很多表示日期时间中各个部分的常量字段。 返回值 字段 说明 static int AM 指示从午夜到中午之前这段时间的 AM_PM 字段值。 static int DATE get 和 set 的字段,指示一个月中的某天。 static int DAY_OF_MONTH get 和 set 的字段,指示一个月中的某天。 static int DAY_OF_WEEK get 和 set 的字段,指示一个星期中的某天。 static int DAY_OF_YEAR get 和 set 的字段,指示当前年中的天数。 static int HOUR get 和 set 的字段,指示上午或下午的小时。 static int HOUR_OF_DAY get 和 set 的字段,指示一天中的小时。 static int MINUTE get 和 set 的字段,指示一小时中的分钟。 static int MONTH 指示月份的 get 和 set 的字段。 static int PM 指示从中午到午夜之前这段时间的 AM_PM 字段值。 static int SECOND get 和 set 的字段,指示一分钟中的秒。 static int WEEK_OF_MONTH get 和 set 的字段,指示当前月中的星期数。 static int WEEK_OF_YEAR get 和 set 的字段,指示当前年中的星期数。 static int YEAR 表示年的 get 和 set 的字段。 表9 Calendar类中的日期字段 Calendar类提供了丰富的操作方法,可以单独对年、月、日、时、分、秒等字段单独读取,也可以对星期设置,常用方法如下: 返回 方法 说明 void add(int field, int amount) 根据日历的规则,为给定的日历字段添加或减去指定的时间量。 boolean after(Object when) 判断此 Calendar 表示的时间是否在指定 Object 表示的时间之后,返回判断结果。 boolean before(Object when) 判断此 Calendar 表示的时间是否在指定 Object 表示的时间之前,返回判断结果。 int get(int field) 返回给定日历字段的值。 int getActualMaximum(int field) 给定此 Calendar 的时间值,返回指定日历字段可能拥有的最大值。 int getActualMinimum(int field) 给定此 Calendar 的时间值,返回指定日历字段可能拥有的最小值。 Date getTime() 返回一个表示此 Calendar 时间值(从历元至现在的毫秒偏移量)的 Date 对象。 long getTimeInMillis() 返回此 Calendar 的时间值,以毫秒为单位。 void set(int field, int value) 将给定的日历字段设置为给定值。 void set(int year, int month, int date) 设置日历字段 YEAR、MONTH 和 DAY_OF_MONTH 的值。 void set(int year, int month, int date, int hourOfDay, int minute) 设置日历字段 YEAR、MONTH、DAY_OF_MONTH、HOUR_OF_DAY 和 MINUTE 的值。 void set(int year, int month, int date, int hourOfDay, int minute, int second) 设置字段 YEAR、MONTH、DAY_OF_MONTH、HOUR、MINUTE 和 SECOND 的值。 void setTime(Date date) 使用给定的 Date 设置此 Calendar 的时间。 void setTimeInMillis(long millis) 用给定的 long 值设置此 Calendar 的当前时间值。 表10 Calendar类常用方法 代码演示:Calendar的使用 import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; public class Demo8 { public static void main(String[] args) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Calendar cale = Calendar.getInstance(); cale.set(2009, 8, 20);// 年月日同时设置 ① cale.set(Calendar.DAY_OF_WEEK, 2); ② Date date1 = cale.getTime(); ③ System.out.println(sdf.format(date1)); cale.set(Calendar.MONTH, 3); ④ cale.set(Calendar.DAY_OF_MONTH, 28); ⑤ cale.set(Calendar.YEAR, 1978); ⑥ Date date2 = cale.getTime(); System.out.println(sdf.format(date2)); } } 代码解析: ① 可以使用set方法对年月日时分秒同时设置。 ② 把天定位到星期一,Calendar中认为第一天是星期天,设置2就是星期一。 ③ Calendar类型转换为日期时间等价的Date类型。 ④ 单独设置月。 ⑤ 单独设置日。 ⑥ 单独设置年。 代码输出结果: 2009-09-21 17:21:37 1978-04-28 17:21:37 Q 老师,为什么通过Calendar设置月与输出差1个月? A 不是差一个月,而是在Calendar中对月份的计算是从0开始的,因此设置月份11其实就是中国的十二月。 5. Java对集合的操作 Java中学习了集合的操作,比如:排序、搜索等,Java中用java.util.Arrays对数组操作,使用java.util.Collections对集合框架中List操作。他们都是工具类,类中的方法全部都是静态方法。  Arrays中的方法 1. void Arrays.sort(T[]) 对数组中的元素按照升序进行排序。T代表某一数据类型。 代码演示:binarySearch使用 public static void main(String[] args) { int[] arrs=new int[]{12,54,12,8765,123,34,54,23,67}; Arrays.sort(arrs); for (int i : arrs) { System.out.print(i+" "); } } 代码输出结果: 12 12 23 34 54 54 67 123 8765 在sort方法中,遇到对象数组的排序时,要给对象提供排序的依据,实现Comparator接口,可以在接口的compare方法中指定排序规则,实现Comparator接口的对象称为比较器。 有一个Student类的数组,现在按照年龄进行升序排序,那么Comparator接口compare方法实现如下: 代码演示:compare重新按年龄实现 class Student { String name; int age; public Student(String name, int age) { super(); this.name = name; this.age = age; } public String toString() { return name + "," + age; } } class StuCom implements Comparator<Student> { ① public int compare(Student stu1, Student stu2) { ② if (stu1.age > stu2.age) { return 1; } else if (stu1.age == stu2.age) { return 0; } else { return -1; } } } public static void main(String[] args) { Student[] stus = new Student[] { new Student("小美", 21), new Student("阿聪", 22), new Student("武大郎", 28), new Student("阮小七", 26), new Student("晁盖", 30), new Student("鲁智深", 29), new Student("孙二娘", 26), new Student("扈三娘", 23), new Student("武松", 24) }; Arrays.sort(stus, new StuCom()); for (Student student : stus) { System.out.println(student); } } 代码解析: ① 定义一个比较器,必须实现Comparator接口,否则系统无法对一个对象数组进行搜索规则。 ② 实现Comparator接口的compare方法,对该方法中的两个参数进行比较,就是制定了比较的规则。 代码输出结果: 小美,21 阿聪,22 扈三娘,23 武松,24 阮小七,26 孙二娘,26 武大郎,28 鲁智深,29 晁盖,30 2. List Arrays.asList(Object[] objs) 把指定的数组转换为List的对象。 代码演示:asList使用 import java.util.Arrays; import java.util.List; public class Demo9 { public static void main(String[] args) { String[] strs={"aaa","bbb","ccc","ddd","eee","fff","ggg","hhh","iii","jjj"}; List list=Arrays.asList(strs); for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i)); } } } 3. int Arrays.binarySearch(T[] objs, key) 在数组objs中查找key的位置,返回key的下标,如果查找不到key,则返回负值。 int Arrays.binarySearch(T[] objs,int fromIndex,int toIndex , key) 在数组objs中从fromIndex到toIndex位置上查找key,返回key的下标,如果查找不到,返回一个负值。 在binarySearch方法调用之前一定要保证数组已经是排序的,如果没有排序,可以使用Arrays.sort(T[]) 进行排序,然后再进行查找。 代码演示:binarySearch使用 public static void main(String[] args) { String[] strs={"aaa","bbb","ccc","ddd","eee","fff","ggg","hhh","iii","jjj"}; Arrays.sort(strs); System.out.println(Arrays.binarySearch(strs, "ccc")); System.out.println(Arrays.binarySearch(strs, 4,8,"ggg")); System.out.println(Arrays.binarySearch(strs, 4,8,"aaa")); } 如果数组是一个自定义的对象数组,那么搜索之前要先指定比较器。 代码演示:binarySearch搜索对象使用 class StuCom implements Comparator<Student> { ① public int compare(Student stu1, Student stu2) { if (stu1.age > stu2.age) { return 1; } else if (stu1.age == stu2.age && stu1.name.equals(stu2.name)) { return 0; } else { return -1; } } } public static void main(String[] args) { Student[] stus = new Student[] { new Student("小美", 21), new Student("阿聪", 22), new Student("武大郎", 28), new Student("阮小七", 26), new Student("晁盖", 30), new Student("鲁智深", 29), new Student("孙二娘", 26), new Student("扈三娘", 23), new Student("武松", 24) }; Student s = new Student("晁盖", 30); System.out.println(Arrays.binarySearch(stus, s, new StuCom())); ② } 代码解析: ① 该比较器规定了要比较的类型就是Student类型,因此这里使用泛型。 ② 指定了对象数组,对象和比较器的方法进行搜索。结果返回搜索到的对象在数组中的下标。 除了上面介绍Arrays的方法外,还有一些其它的方法: 方法 说明 T[] copyOf(T[] t,int length) 把一个数组赋值到长度是length的新数组中。T表示数据类型。 fill(T[] t,N newValue) 用一个固定值填充数组中所有元素。 表11 Arrays其他常用方法。  Collections类 Collections类与Arrays类一样都提供了一系列的静态方法,只是Arrays主要操作数组,而Collections主要操作List集合,同时还有对Set的相关操作。 代码演示:Collections操作 import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Demo10 { static class Student implements Comparable { ① String name; int age; public Student(String name, int age) { super(); this.name = name; this.age = age; } public String toString() { return name + "," + age; } public int compareTo(Object o) { ② Student stu = (Student) o; if (this.age > stu.age) { return 1; } else if (this.age == stu.age && this.name.equals(stu.name)) { return 0; } else { return -1; } } } public static void main(String[] args) { List<Student> list = new ArrayList<Student>(); Student[] stus = new Student[] { new Student("小美", 21), new Student("阿聪", 22), new Student("武大郎", 28), new Student("阮小七", 26), new Student("晁盖", 30), new Student("鲁智深", 29), new Student("孙二娘", 26), new Student("扈三娘", 23), new Student("武松", 24) }; Collections.addAll(list, stus); ③ Collections.sort(list); ④ for (Student student : stus) { System.out.println(student); } Student stu = new Student("鲁智深", 29); int pos = Collections.binarySearch(list, stu); ⑤ System.out.println(pos); } } 代码解析: ① 在List中查找一个对象时,该对象必须实现Comparable接口。 ② compareTo方法中使用当前对象与参数对象进行比较。 ③ 把一个数组对象复制到List对象中用方法Collections.addAll(……)方法 ④ 对List集合中的元素按照自然顺序排序。 ⑤ 二分法查找,在List集合中查找Student对象,要求Student对象必须实现Comparable接口。 Collections的主要操作有: 1. int binarySearch(List<? extends Comparable<? super T>> list, T key) 该方法是寻找T对象在List中匹配元素的位置。要求List集合中必须全部都是T对象,T对象必须实现Comparable接口,如果查找成功返回对象在List中的位置,否则返回负数。该方法执行前首先要对List对象中的元素排序,该方法还有一个重载方法是: int binarySearch(List<? extends T> list, T key, Comparator<? super T> c) 该方法也是查找T对象在List中的位置,List集合中必须全部是T元素,但是不要去T必须实现Comparable接口,而是要求传入一个比较器。 2. sort(List<T> list) 对List中的元素按照自然排序。要按照用户自定义方式进行排序,必须实现Comparator接口。 sort (List<T> list, Comparator<? super T> c) 根据指定比较器产生的顺序对指定列表进行排序。 3. swap(List<?> list, int i, int j) 在指定列表的指定位置处交换元素。 4. reverse(List<?> list) 反转指定列表中元素的顺序。 在Collections中还有其他一些方法,可以参考JavaDoc文档。 6. java.lang.Math类 在java.lang.Math类中,包含用于执行基本数学运算的方法,如指数、对数、平方根和三角函数等。Math类中定义的所有方法和常量全部都是静态的,使用非常方便。定义的常量主要有两个:Math.E和Math.PI分别表示自然对数的底数和圆周率。 Math类中主要的方法有: 返回 方法 说明 static T abs(T a) 返回 long 值的绝对值。 static double acos(double a) 返回一个值的反余弦;返回的角度范围在 0.0 到 pi 之间。 static double atan(double a) 返回一个值的反正切;返回的角度范围在 -pi/2 到 pi/2 之间。 static double ceil(double a) 返回最小的(最接近负无穷大)double 值,该值大于等于参数,并等于某个整数。 static double cos(double a) 返回角的三角余弦。 static double floor(double a) 返回最大的(最接近正无穷大)double 值,该值小于等于参数,并等于某个整数。 static double log(double a) 返回 double 值的自然对数(底数是 e)。 static double log10(double a) 返回 double 值的底数为 10 的对数。 static T max(T a, T b) 返回两个 double 值中较大的一个。 static T min(T a, T b) 返回两个 long 值中较小的一个。 static T pow(T a, T b) 返回第一个参数的第二个参数次幂的值。 static double random() 返回带正号的 double 值,该值大于等于 0.0 且小于 1.0。 static int round(float a) 返回最接近参数的 int。 static double sin(double a) 返回角的三角正弦。 static double sqrt(double a) 返回正确舍入的 double 值的正平方根。 static double tan(double a) 返回角的三角正切。 表12 Math类中的常见静态方法
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值