您的位置:首页 > 编程语言 > Java开发

java.util —— 工具类

2016-03-09 16:16 615 查看
工具类的存在,是为了平衡,Java 彻底的面向对象(everything is object. 的极端;),也即并非所有的东西都可抽象为类的,但又要有类的形式,工具类便由此诞生。

工具类不做实例化,工具类中可调用的成员函数均为static,即通过工具类的类名即可访问;

工具类的使用,避免了 new 操作,以及大量的实例化对象;

0. Random

private static Random rand = new Random(47);

rand 作为一个随机 index;(47 是该随机数的种子值)

1. java.util.Arrays

copyOf

在实现 Stack 类时,每执行一次 push 的操作,需要首先判断当前所分配存储空间是否已经使用完备:

private void ensureCapacity() {
if (size == elements.length) {
elements = Arrays.copyOf(elements, 2*size+1);
}
}


asList

List<Shape> shapeList = Arrays.asList(new Circle(), new Square(), new Triangle());


2. java.util.Vector

Vector 类的显著特性即是支持枚举(迭代);

Vectot<ClassName> records = new Vector<>();
Enumeration recordEnum = records.elements();
while (recordEnum.hasMoreElements()) {
ClassName each = (ClassName)recordEnum.nextElement();
}


其中 Enumeration 是 java 内置接口:

public interface Enumeration<E> {
boolean hasMoreElements();
E nextElement();
}


3. Calendar

public boolean isBabyBoomer() {

Calendar gmtCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
gmtCal.set(1946, Calendar.JANUARY, 1, 0, 0, 0);
Date start =  gmtCal.getTime();
gmtCal.set(1965, Calendar.JANUARY, 1, 0, 0, 0);
Date end = gmtCal.getTime();

return birthDate.compareTo(start) >= 0 &&
birthDate.compareTo(end) < 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: