java10 - 泛型与枚举

时间:2023-03-09 15:06:57
java10 - 泛型与枚举

java10泛型与枚举

泛型和枚举都是JDK1.5版本之后加入的新特性,泛型将程序代码的类型检查提前到了编译期间进行,枚举类型增强了程序代码的健壮性。

1.泛型类

class VariableType<T> { // 此处可以随便写标识符号,T是type的简称
private T var; // var的类型由T指定,即:由外部指定
public T getVar() { // 返回值的类型由外部决定 ,泛型方法
return var;
}
public void setVar(T var) { // 设置的类型也由外部决定
this.var = var;
}
}; public static void main(String args[]) {
VariableType <String> p = new VariableType <String>(); // 里面的var类型为String类型
p.setVar("it"); // 设置字符串
System.out.println(p.getVar().length()); // 取得字符串的长度
}

2.泛型方法

// T 为参数类型
public static void main(String[] args) {
variableType(1);
variableType(1.0);
} public static <T> void variableType(T a) {
System.out.println(a.getClass());
}

3.泛型接口的定义和使用

package com.rimi.Test;

import java.util.Date;

interface Show<T,U>{
void show(T t,U u);
} class ShowTest implements Show<String,Date>{
@Override
public void show(String str,Date date) {
System.out.println(str);
System.out.println(date);
}
} public class TestDemo {
public static void main(String[] args) {
ShowTest showTest=new ShowTest();
showTest.show("Hello",new Date());
}
}

4.比较任意类型的两个数的大小

public static void main(String[] args) {
System.out.println(get(1,2));
} public static <T extends Comparable> T get(T t1, T t2) { // 添加类型限定
if (t1.compareTo(t2) >= 0)
{
return t2;
}
return t1;
}

5.枚举

// 枚举定义
public enum Color {
RED, GREEN, BLANK, YELLOW
}
// 枚举使用
public static void main(String[] args) {
System.out.println( isRed( Color.BLANK ) ) ; //结果: false
System.out.println( isRed( Color.RED ) ) ; //结果: true }
// 枚举值的使用
static boolean isRed( Color color ){
if ( Color.RED.equals( color )) {
return true ;
}
return false ;
}
public enum Color {
RED, GREEN, BLANK, YELLOW
} public static void main(String[] args) {
showColor(Color.RED);
} static void showColor(Color color) {
switch (color) {
case BLANK:
System.out.println(color);
break;
case RED:
System.out.println(color);
break;
default:
System.out.println(color);
break;
}
}
//自定义函数
public enum Color {
RED("红色", 1), GREEN("绿色", 2), BLANK("白色", 3), YELLO("黄色", 4);
private String name;
private int index;
private Color(String name, int index) {
this.name = name;
this.index = index;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
} public static void main(String[] args) {
// 输出某一枚举的值
System.out.println(Color.RED.getName());
System.out.println(Color.RED.getIndex());
// 遍历所有的枚举
for (Color color : Color.values()) {
System.out.println(color + " name: " + color.getName() + " index: " + color.getIndex());
}
}