Java 中的 6 颗语法糖
SegmentFault
共 4733字,需浏览 10分钟
·
2020-10-16 00:05
泛型与类型擦除 自动装箱与拆箱 变长参数 增强for循环 内部类 枚举类
/**
* 在源代码中存在泛型
*/
public static void main(String[] args) {
Map
map = new HashMap (); map.put("hello","你好");
String hello = map.get("hello");
System.out.println(hello);
}
public static void main(String[] args) {
HashMap map = new HashMap(); //类型擦除
map.put("hello", "你好");
String hello = (String)map.get("hello");//强制转换
System.out.println(hello);
}
public static void main(String[] args) {
Integer a = 1;
int b = 2;
int c = a + b;
System.out.println(c);
}
public static void main(String[] args) {
Integer a = Integer.valueOf(1); // 自动装箱 byte b = 2; int c = a.intValue() + b;//自动拆箱 System.out.println(c);}
public class Varargs {
public static void print(String... args) {
for(String str : args){
System.out.println(str);
}
}
public static void main(String[] args) {
print("hello", "world");
}
}
public class Varargs {
public Varargs() {
}
public static void print(String... args) {
String[] var1 = args;
int var2 = args.length;
//增强for循环的数组实现方式
for(int var3 = 0; var3 < var2; ++var3) {
String str = var1[var3];
System.out.println(str);
}
}
public static void main(String[] args) {
//变长参数转换为数组
print(new String[]{"hello", "world"});
}
}
public static void main(String[] args) {
String[] params = new String[]{"hello","world"};
//增强for循环对象为数组
for(String str : params){
System.out.println(str);
}
List
lists = Arrays.asList("hello","world"); //增强for循环对象实现Iterable接口
for(String str : lists){
System.out.println(str);
}
}
public static void main(String[] args) {
String[] params = new String[]{"hello", "world"};
String[] lists = params;
int var3 = params.length;
//数组形式的增强for退化为普通for
for(int str = 0; str < var3; ++str) {
String str1 = lists[str];
System.out.println(str1);
}
List var6 = Arrays.asList(new String[]{"hello", "world"});
Iterator var7 = var6.iterator();
//实现Iterable接口的增强for使用iterator接口进行遍历
while(var7.hasNext()) {
String var8 = (String)var7.next();
System.out.println(var8);
}
}
public class Outer {
class Inner{
}
}
class Outer$Inner {
Outer$Inner(Outer var1) {
this.this$0 = var1;
}
}
public enum Fruit {
APPLE,ORINGE
}
//继承java.lang.Enum并声明为final
public final class Fruit extends Enum
{
public static Fruit[] values()
{
return (Fruit[])$VALUES.clone();
}
public static Fruit valueOf(String s)
{
return (Fruit)Enum.valueOf(Fruit, s);
}
private Fruit(String s, int i)
{
super(s, i);
}
//枚举类型常量
public static final Fruit APPLE;
public static final Fruit ORANGE;
private static final Fruit $VALUES[];//使用数组进行维护
static
{
APPLE = new Fruit("APPLE", 0);
ORANGE = new Fruit("ORANGE", 1);
$VALUES = (new Fruit[] {
APPLE, ORANGE
});
}
}
评论