Java 拾遗(二)

一、Java 枚举类

Java枚举类可以限制取值,实现单例设计模式等功能。

枚举类的构造方法是用private修饰的。枚举类的所有实例必须在类的第一行列出,否则这个枚举类不会产生对象。
而且这些实例都是public static void。

1.一个简单的例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
enum CarType{
//车型枚举类
First("小型轿车"), //不同枚举元素用逗号分割开来
Second("中型轿车"),
Third("大型车"),
Fourth("SUV"),
Fifth("MPV"),
Sixth("跑车"),
Seventh("皮卡"),
Eighth("面包车"),
Ninth("卡车"),
Tenth("客车"),
Eleventh("其他"); //枚举完毕使用分号
private final String value;
CarType(String value) { //使用构造方法
this.value = value;
}
public String getValue() {
return value; //实例方法来获取枚举元素的值
}
}

在调用时:

1
2
3
4
public void text(){
CarType rs1 = CarType.First;
String rs2 = CarType.First.getValue();
}

2.枚举类方法

每个枚举类都有一个values方法,该方法可以遍历枚举类的所有实例:

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
public class Test {  
public static void tell(Season s)
{

switch(s)
{
case Spring:
System.out.println(s+"春天");
break;
case Summer:System.out.println(s+"夏天");
break;
case Fall:System.out.println(s+"秋天");
break;
case Winter:System.out.println(s+"冬天");
break;
}
}

public static void main(String[] args) {
for(Season s:Season.values()) {
System.out.println(s);
}
tell(Season.Fall);
}
}
enum Season
{
Spring,Summer,Fall,Winter;
}

枚举类的构造方法是 privite 所以不能用new 来创建对象。
可以使用Enum.valueOf(Class c,String s); 创建对象。

1
2
3
4
5
6
public class Test {   
public static void main(String[] args) {
Season s=Enum.valueOf(Season.class, "Summer");
System.out.println(s);
}
}

二、Java Queue接口

Queue接口与List、Set同一级别,都是继承了Collection接口。

Queue队列的一些常用方法:

add 增加一个元索 如果队列已满,则抛出一个IIIegaISlabEepeplian异常
remove 移除并返回队列头部的元素 如果队列为空,则抛出一个NoSuchElementException异常
element 返回队列头部的元素 如果队列为空,则抛出一个NoSuchElementException异常
offer 添加一个元素并返回true 如果队列已满,则返回false
poll 移除并返问队列头部的元素 如果队列为空,则返回null
peek 返回队列头部的元素 如果队列为空,则返回null
put 添加一个元素 如果队列满,则阻塞
take 移除并返回队列头部的元素 如果队列为空,则阻塞