Date类

常用时间元字符
– y, yy:2位数字年份,如14
– yyyy:4位数字年份,如2014
– M, MM:2位数字月份,如08
– MMM:汉字月份,如八月
– d, dd:2位数字日期,如09, 22
– a:上午或下午
– H, HH:2位数字小时(00-23)
– h, hh:2位数字小时(am/pm,01-12)
– m, mm:2位数字分
– s, ss:2位数字秒
– E, EE:星期

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
import java.util.Date; 
import java.text.SimpleDateFormat;

public class Example7_1
{
public static void main(String args[])
{
Date currentTime = new Date(); //获取本地当前时间
System.out.println("Current time: " + currentTime); //Current time: Sun Dec 08 23:58:03 CST 2024

//格式化
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd ");
System.out.println("Current time: " + sdf1.format(currentTime)); //Current time: 2024-12-08

SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss(a)(EE)");
System.out.println("Current time: " + sdf2.format(currentTime)); //Current time: 2024-12-08 23:58:03(下午)(周日)

long time = -1000L;
Date date = new Date(time);
System.out.println(time + "ms: " + sdf2.format(date)); //-1000ms: 1970-01-01 07:59:59(上午)(周四)

time = 1000L;
date = new Date(time);
System.out.println(time + "ms: " + sdf2.format(date)); //1000ms: 1970-01-01 08:00:01(上午)(周四)
}
}

Calendar类

使用Calendar类的static方法getInstance()可以初始化一个日历对象
Calendar calendar = Calendar.getInstance();
方法:将日历翻到任何一个时间,当参数year取负数时表示公元前。
– public final void set(int year, int month, int date)
– public final void set(int year, int month, int date, int hour, int minute)
– public final void set(int year, int month, int date, int hour, int minute, int second)
方法public int get(int field)可以获取有关年份、月份、小时、星期等信息
calendar.get(Calendar.MONTH); 返回一个整数,0表示一月,1表示二月,等。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import java.util.*; 
public class Example7_2
{
public static void main(String args[])
{
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
String day_of_week = String.valueOf(calendar.get(Calendar.DAY_OF_WEEK)-1);
System.out.println(day_of_week); //3 //(星期三)
calendar.set(1931,8,18);
long timeOne = calendar.getTimeInMillis();
calendar.set(1945,7,15);
long timeTwo = calendar.getTimeInMillis();
long days = (timeTwo-timeOne)/(1000*60*60*24);
System.out.println("1945年8月15日和1931年9月18日相隔: " + days + "天"); //5080天
}
}
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
// 打印月日历
import java.util.*;
public class Example7_3
{
public static void main(String args[])
{
Calendar calendar = Calendar.getInstance();
calendar.set(1931,8,1);
int day_of_week = calendar.get(Calendar.DAY_OF_WEEK)-1;
String a[] = new String[day_of_week+30];
for(int i=0; i<day_of_week; i++) //前面空白
a[i] = "";

for(int i=day_of_week,n=1; i<day_of_week+30; i++)
{
a[i] = String.valueOf(n); //打印日期
n++;
}
for(int i=0;i<a.length;i++)
{
if(i%7==0&&i!=0) //控制换行
System.out.printf("\n");
System.out.printf("%5s",a[i]);
}
}
}

Math类与BigInteger类

Math类

E = 2.7182828284590452354
PI = 3.14159265358979323846
常用方法
– public static long abs(double a):返回a的绝对值
– public static double max(double a, double b):返回a, b的最大值
– public static double min(double a, double b):返回a, b的最小值
– public static double random():产生一个0到1之间的随机数,范围是[0,1)
– public static double pow(double a, double b):返回a的b次幂
– public static double sqrt(double a):返回a的平方根
– public static double log(double a):返回a的对数
– public static double sin(double a):返回正弦值
– public static double asin(double a):返回反正弦

BigInteger类

提供任意精度的整数运算(类似高精)

eg: 创建一个十进制的BigInteger对象public BigInteger(String val)
参数val中如果含有非数字字符就会发生NumberFormatException异常
常用方法
– public BigInteger add(BigInteger val):返回当前大整数对象与参数指定的大整数对象的和
– public BigInteger subtract(BigInteger val):返回当前大整数对象与参数指定的大整数对象的差
– public BigInteger multiply(BigInteger val):返回当前大整数对象与参数指定的大整数对象的积
– public BigInteger divide(BigInteger val):返回当前大整数对象与参数指定的大整数对象的商
– public BigInteger remainder(BigInteger val):返回当前大整数对象与参数指定的大整数对象的余
– public int compareTo(BigInteger val):返回当前大整数对象与参数指定的大整数的比较结果,返回值是1、-1或0,分别表示当前大整数对象大于、小于或等于参数指定的大整数
– public BigInteger abs():返回当前大整数对象的绝对值
– public BigInteger pow(int exponent):返回当前大整数对象的exponent次幂
– public String toString():返回当前大整数对象十进制的字符串表示
– public String toString(int p):返回当前大整数对象p进制的字符串表示

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
import java.math.*; 
public class Example7_6
{
public static void main(String args[])
{
BigInteger n1 = new BigInteger("987654321987654321987654321");
BigInteger n2 = new BigInteger("123456789123456789123456789");
System.out.println("add: " + n1.add(n2));
System.out.println("subtract: " + n1.subtract(n2));
System.out.println("multiply: " + n1.multiply(n2));
System.out.println("divide: " + n1.divide(n2));
BigInteger m = new BigInteger("77889988");
BigInteger COUNT = new BigInteger("0");
BigInteger ONE = new BigInteger("1");
BigInteger TWO = new BigInteger("2");
for( BigInteger i=TWO; i.compareTo(m)<0; i=i.add(ONE) )
{
if((n1.remainder(i).compareTo(BigInteger.ZERO))==0)
{
COUNT = COUNT.add(ONE);
}
}
System.out.println(COUNT);
}
}

数字格式化

– public void setMaximumFractionDigits(int newValue)
– public void setMinimumFractionDigits(int newValue)
– public void setMaximumIntegerDigits(int newValue)
– public void setMinimumIntegerDigits(int newValue)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import java.text.NumberFormat; 
public class Example_Format
{
public static void main(String args[])
{
double a = Math.sqrt(10);
System.out.println("Before: " + a);
NumberFormat f = NumberFormat.getInstance(); //实例化一个NumberFormat对象
f.setMaximumFractionDigits(5); //调整小数5位
f.setMinimumIntegerDigits(3); //调整整数3位
String s = f.format(a); //对象f可调用String format(double number)格式化数字number
System.out.println("After: " + s);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class MyNumberFormat 
{
public String format(double a, int n)
{
String str = String.valueOf(a); //num->string
int index = str.indexOf(".");
String temp = str.substring(index+1);
int fractionLeng = temp.length();
n = Math.min(fractionLeng, n);
str = str.substring(0,index+n+1);
return str;
}
}
public class Example_Format2
{
public static void main(String args[])
{
double a = Math.sqrt(10);
System.out.println("Before: " + a);
MyNumberFormat myFormat=new MyNumberFormat();
System.out.println("After: " + myFormat.format(a,5));
}
}

LinkedList泛型类

LinkedList<E>泛型类创建链表结构的数据对象

  • 每个节点含有一个数据和下一个节点的引用(单链表)
  • 含有一个数据并含有上一个节点的引用和下一个节点的引用(双链表)
  • 节点的索引从0开始
  • 适合动态地改变存储的数据
  • 节点是自动连接在一起的,不需要我们去做连接,也就是说,不需要我们去操作安排节点中所存放的下一个或上一个节点的引用。
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
// 方法:
public boolean add(E element)
//向链表末尾添加一个新的节点,该节点中的数据是参数element指定的对象。
public void add(int index, E element)
//向链表的指定位置添加一个新的节点,该节点中的数据是参数element指定的对象。
public void addFirst(E element)
//向链表的头添加新节点,该节点中的数据是参数element指定的对象。
public E removeFirst()
//删除第一个节点,并返回这个节点中的对象。
public E removeLast()
//删除最后一个节点,并返回这个节点中的对象。
public E get(int index)
//得到链表中指定位置处节点中的对象。
public E getFirst()
//得到链表中第一个节点中的对象。
public E getLast()
//得到链表中最后一个节点中的对象。
public int indexOf(E element)
//返回含有数据element的节点在链表中首次出现的位置,如果链表中无此节点则返回-1
public int lastIndexOf(E element)
//返回含有数据element的节点在链表中最后出现的位置,如果链表中无此节点则返回-1
public E set(int index, E element)
//将当前链表index位置节点中的对象替换为参数element指定的对象,并返回被替换的对象。
int size()
//返回链表的长度,即节点的个数。
public boolean contains(Object element)
//判断链表节点中是否有节点包含对象element。
public Object clone()
//得到当前链表的一个克隆链表,该克隆链表中节点数据的改变不会影响到当前链表中节点的数据,反之亦然。
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
36
37
38
39
40
41
42
43
44
45
46
import java.util.*;  
class Student
{
String name;
int score;
Student(String name, int score)
{
this.name = name;
this.score = score;
}
}
public class Example7_7
{
public static void main(String args[])
{
LinkedList<Student> mylist = new LinkedList<Student>();
Student stu1 = new Student("S1",78);
Student stu2 = new Student("S2",98);
mylist.add(stu1);
mylist.add(stu2);
int number = mylist.size();
for(int i=0; i<number; i++)
{
Student temp = mylist.get(i);
System.out.printf("%s:%d\n",temp.name,temp.score);
}
}
}

public class Example7_7
{
public static void main(String args[])
{
LinkedList<Student> mylist = new LinkedList<Student>();
Student stu1 = new Student("S1",78);
Student stu2 = new Student("S2",98);
mylist.add(stu1);
mylist.add(stu2);
Iterator<Student> iter = mylist.iterator();
while(iter.hasNext())
{
Student temp = iter.next();
System.out.printf("%s:%d\n",temp.name,temp.score);
}
}
}

HashSet泛型类

类似数学上的集合,可以进行”交”、”并”、”差”等运算。

  • 集合不允许有相同的元素
  • 集合对象的初始容量(capacity)是16个字节,装载因子(load factor)是0.75,也就是说,如果集合添加的元素超过总容量的75%时,集合的容量将增加一倍
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
public boolean add(E o)
//向集合添加参数指定的元素。
public void clear()
//清空集合,使集合不含有任何元素。
public boolean contains(Object o)
//判断集合是否包含参数指定的数据。
public boolean isEmpty()
//判断集合是否为空。
public boolean remove(Object o)
//删除参数指定的元素。
public int size()
//返回集合中元素的个数。
Object[] toArray()
//将集合元素存放到数组中,并返回这个数组。
boolean containsAll(HanshSet set)
//判断当前集合是否包含参数指定的集合。
public Object clone()
//得到当前集合的一个克隆对象,该对象中元素的改变不会影响到当前集合中的元素,反之亦然。

//并
boolean addAll(HashSet set)
//交
boolean retainAll(HashSet set)
//差
boolean removeAll(HashSet set)
// 参数指定的集合和当前集合必须是同种类型的集合,否则上述方法返回false
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
import java.util.*;  
class Student
{
String name;
int score;
Student(String name, int score)
{
this.name = name;
this.score = score;
}
}
public class Example7_10
{
public static void main(String args[])
{
Student stu1 = new Student("S1",78);
Student stu2 = new Student("S2",98);
HashSet<Student> set = new HashSet<Student>();
HashSet<Student> subset = new HashSet<Student>();
set.add(stu1);
set.add(stu2);
subset.add(stu1);
System.out.println("set contains subset:" + set.containsAll(subset)); //判断当前集合是否包含参数指定的集合。
Object s[] = set.toArray(); //将集合元素存放到数组中,并返回这个数组。
for(int i=0; i<s.length;i++)
{
System.out.printf("%s:%d\n",((Student)s[i]).name, ((Student)s[i]).score);
}
}
}
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
import java.util.*;  
class Student
{
String name;
int score;
Student(String name, int score)
{
this.name = name;
this.score = score;
}
}
public class Example7_11
{
public static void main(String args[])
{
Student stu1 = new Student("S1",78);
Student stu2 = new Student("S2",98);
HashSet<Student> set = new HashSet<Student>();
HashSet<Student> subset = new HashSet<Student>();
set.add(stu1);
set.add(stu2);
subset.add(stu1);

HashSet<Student> tempSet = (HashSet<Student>)set.clone(); //得到当前集合的一个克隆对象
tempSet.removeAll(subset); //差
Iterator<Student> iter = tempSet.iterator();
while(iter.hasNext())
{
Student temp = iter.next();
System.out.printf("%s:%d\n",temp.name,temp.score);
}
}
}

HashMap<K,V>泛型类

散列表/散列映射对象

  • 散列映射用于存储键/值数据对,允许把任何数量的键/值数据对存储在一起。
  • 键(Key)不可以发生逻辑冲突,即不要对两个数据项使用相同的键.如果出现两个数据项使用相同的键,那么,先前散列映射中的键/值对将被替换。
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
36
37
public void clear()
//清空散列映射。
public Object clone()
//返回当前散列映射的一个克隆。
public boolean containsKey(Object key)
//如果散列映射有键/值对使用了参数指定的键,方法返回true,否则返回false。
public boolean containsValue(Object value)
//如果散列映射有键/值对的值是参数指定的值,方法返回true,否则返回false。
public V get(Object key)
//返回散列映射中使用key做键的键/值对中的值。
public boolean isEmpty()
//如果散列映射不含任何键/值对,方法返回true,否则返回false。
public V remove(Object key)
//删除散列映射中键为参数指定的键/值对,并返回键对应的值。
public int size()
//返回散列映射的大小,即键/值对的数目。

//遍历
//获得散列映射中所有的值
import java.util.*;
public class Example7_12
{
public static void main(String args[])
{
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("a", 1);
map.put("b", 2);

Collection<Integer> collection = map.values();
Iterator<Integer> iter = collection.iterator();
while(iter.hasNext())
{
Integer temp = iter.next();
System.out.println(temp.toString());
}
}
}

TreeSet泛型类

树集

  • 存放到树集中的对象按对象的字符串表示升序排列
  • 树集中不容许出现大小相等的两个节点
    如果允许相同,则compareTo方法要更改
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public boolean add(E o)
//向树集添加对象,添加成功返回true,否则返回false。
public void clear()
//清空树集中的所有对象。
public void contains(Object o)
//如果包含对象o,方法返回true,否则返回false 。
public E first()
//返回树集中的第一个对象(最小的对象)。
public E last()
//返回最后一个对象(最大的对象)。
public isEmpty()
//判断是否是空树集,如果树集不含对象返回true 。
public boolean remove(Object o)
//删除树集中的对象o。
public int size()
//返回树集中对象的数目。

创建树集时可自己规定树集中的对象按着什么样的”大小”顺序排列。

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
36
37
38
39
40
41
42
import java.util.*;  
class Student implements Comparable // 自定义排序方式
{
String name;
int score;
Student(String name, int score)
{
this.name = name;
this.score = score;
}
public int compareTo(Object o)
{
Student stu = (Student)o;
return (this.score - stu.score); //分数低在前
}

//若允许成绩相同
/* public int compareTo(Object o)
{
Student stu = (Student)o;
if(this.score==stu.score) return 1;
else return (this.score - stu.score);
} */

}
public class Example7_13
{
public static void main(String args[])
{
TreeSet<Student> mytree = new TreeSet<Student>();
Student stu1 = new Student("S1",78);
Student stu2 = new Student("S2",98);
mytree.add(stu1);
mytree.add(stu2);
Iterator<Student> iter = mytree.iterator();
while(iter.hasNext())
{
Student temp = iter.next();
System.out.printf("%s:%d\n",temp.name,temp.score);
}
}
}
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
import java.util.*;  
class Student
{
String name;
int score;
Student(String name, int score)
{
this.name = name;
this.score = score;
}
}
class StudentComparator implements Comparator //定义排序
{
String name;
int score;
//Comparator是java.util包中的一个接口,compare(Object o1,Object o2)是接口中的方法。
public int compare(Object o1, Object o2)
{
return ( ((Student)o1).score - ((Student)o2).score); //从低到高分
}
}
public class ExampleComparator
{
public static void main(String args[])
{
Student [] students = new Student[]{new Student("S1",78), new Student("S2",98)};
Arrays.sort(students, new StudentComparator()); //sort函数
for(int i=0; i<students.length; i++)
{
Student temp = students[i];
System.out.printf("%s:%d\n",temp.name,temp.score);
}
}
}

TreeMap<K,V>泛型类

不像散列映射(HashMap),树映射(TreeMap)保证它的元素按照关键字升序排列

  • TreeMap<K,V>()
    按关键字的大小顺序来排序树映射中的”键/值”对,键的大小顺序是按其字符串表示的字典顺序
  • TreeMap<K,V>(Comparator comp)
    按comp接口规定的大小顺序来排序树映射中的”键/值”对。
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
36
37
38
39
40
41
42
43
44
45
import java.util.*; 
class Student
{
String name = null;
int height, weight;
Student(int w, int h, String name)
{
weight=w;
height=h;
this.name=name;
}
}
class MyKey implements Comparable //排序
{
int number=0;
MyKey(int number)
{
this.number=number;
}
public int compareTo(Object o) //从轻到重
{
MyKey mykey = (MyKey)o;
if(this.number == mykey.number)
return 1;
else
return (this.number - mykey.number);
}
}
public class Example7_14
{
public static void main(String args[])
{
Student s1 = new Student(65,177,"Zhang"), s2 = new Student(85,168,"Li");
TreeMap<MyKey,Student> treemap = new TreeMap<MyKey,Student>();
treemap.put(new MyKey(s1.weight),s1);
treemap.put(new MyKey(s2.weight),s2);
Collection<Student> collection = treemap.values(); //转型
Iterator<Student> iter = collection.iterator();
while(iter.hasNext())
{
Student te=iter.next();
System.out.printf("%s,%d(kg)\n",te.name,te.weight);
}
}
}

Stack泛型类

栈是一种“后进先出”,只能在一端进行输入或输出数据的操作。
向栈中输入数据的操作称为”压栈”,从栈中输出数据的操作称为”弹栈”

1
2
3
4
5
public E push(E item) //压栈
public E pop() //弹栈
public boolean empty() //判断栈是否还有数据
public E peek() // 获取栈顶端的数据,但不删除该数据
public int search(Object data) // 获取数据在栈中的位置,最顶端的位置是1,向下依次增加,如果栈不含此数据,则返回-1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//斐波那契整数序列(Fibonacci sequence)
import java.util.*;
public class Example7_15
{
public static void main(String args[])
{
Stack<Integer> stack=new Stack<Integer>();
stack.push(new Integer(1));
stack.push(new Integer(1));
int k=1;
while(k<=5)
{
Integer F1 = stack.pop();
int f1 = F1.intValue();
Integer F2 = stack.pop();
int f2 = F2.intValue();
Integer temp = new Integer(f1+f2);
System.out.println(temp.toString());
stack.push(temp);
stack.push(F2);
k++;
}
}
}

summary

1 Date类
2 Calendar类
3 Math类与BigInteger类
4 数字格式化
———————— Data Structures
5 LinkedList泛型类 |
6 HashSet泛型类 |
7 HashMap<K,V>泛型类 |
8 TreeSet泛型类 |
9 TreeMap<K,V>泛型类 |
10 Stack泛型类 |

• Queue
– Stack
• List
– ArrayList
– LinkedList
• Set
– HashSet
– LinkedHashSet 根据insertion order
– TreeSet 排序的Set
• Map
– HashMap
– LinkedHashMap 根据insertion order
– TreeMap 排序的Map