1. 程式人生 > 其它 >學習JAVA第十四天

學習JAVA第十四天

裝箱

基本型別直接賦值一個引用型別 Integer I = 10;

拆箱 int i = I;

實際為 Integer I = Integer.valueOf(10); int i = I.intValue();

2.列舉(enum)

簡單情況下,與其他語言的enum相似

enum Light {Red,Yellow,Green};

Light light = Light.Green;

*自定義列舉

enum Direction
{
EAST("東",1), SOUTH("南",2),
WEST("西",3), NORTH("北",4);
private Direction(String desc, int num){
this.desc=desc; this.num=num;
}
private String desc;
private int num;
public String getDesc(){ return desc; }
public int getNum(){ return num; }
}
class EnumDemo2
{
public static void main(String[] args)
{
Direction dir = Direction.NORTH;
for( Direction d : Direction.values())
System.out.println(
d.getDesc() + "," +d.getNum()+ "," + d.ordinal());
}
}

3.註解

在各種語法要素上加上附加資訊,供編譯器或者其他程式使用

@Override 表示覆蓋父類的方法

@Deprecated 表示過時的方法

@SuppressWarnings 表示不讓編譯器產生警告

4.沒用指標的java語言

*引用於指標(引用實質上就是指標)

是受控的,安全的

C語言中有指標,其在java中也有體現

A:用來傳地址 --> 物件

引用型別,引用本身就相當於地址,可修改物件屬性,呼叫物件方法

B:指標運算 --> 陣列

例如C中的 *(p+1),則可以用 args[5]

C:函式指標 --> 介面,lambda表示式等等。

* ==

基本型別:

數值在轉換後進行比較;浮點數以為有誤差,最好不直接用==;boolean無法與int相比較

列舉型別:

因為內部進行了例項化,可直接判斷

引用物件:

可以直接看兩個引用是否一樣,若判斷內容是否一樣,要看equals寫法

String物件:

一定不要用 == ,要用equals,但是字串常量和會進行內部化,相同字串常量是相等的

class TestStringEquals{
public static void main(String[] args) {
String hello = "Hello", lo = "lo";
System.out.println( hello == "Hello"); //正確
System.out.println( Other.hello == hello ); //正確 System.out.println( hello == ("Hel"+"lo") ); //正確
System.out.println( hello == ("Hel"+lo) ); //錯誤

System.out.println( hello == new String("Hello")); //錯誤
System.out.println( hello == ("Hel"+lo).intern()); //正確
}
}
class Other { static String hello = "Hello"; }