1.
public class Equivalence {
public static void main(String[] args){
Integer n1 = new Integer(47);
Integer n2 = new Integer(47);
System.out.println(n1==n2);
}
}
盡管n1, n2均為等于47的整型,即對象的內容是相同的,但對象的引用卻是不同的,因此輸出結果為
false
所以對內容的相同與否判斷應該使用equals方法
System.out.println(n1.equals(n2)) 顯示 true
然而,當創建了自己的類時
class Value{
int i;
}
public class EqualsMethod {
public static void main(String[] args)
{
Value v1 = new Value();
Value v2 = new Value();
v1.i = v2.i = 100;
System.out.println(v1.equals(v2));
v1 = v2;
System.out.println(v1.equals(v2));
}
}
結果仍為
false
true
這是由于equals()的默認行為是比較引用。所以除非在自己的新類中覆蓋equals()方法,否則不可能表現出希望的行為。
2. Java provides the & and | operators. The & operator works exactly the same as the && operator, and the | operation works exactly the same as the || operator with one exception: the & and | operators always evaluate both operands. Therefore, & is referred to as the unconditional AND operator and | is referred to as conditional OR operator.
3. Math.random() 隨機產生在[0,1)的一個雙精度數
random
public static double random()
- Returns a
double
value with a positive sign, greater than or equal to 0.0
and less than 1.0
. Returned values are chosen pseudorandomly with (approximately) uniform distribution from that range.
When this method is first called, it creates a single new pseudorandom-number generator, exactly as if by the expression
new java.util.Random
This new pseudorandom-number generator is used thereafter for all calls to this method and is used nowhere else.
This method is properly synchronized to allow correct use by more than one thread. However, if many threads need to generate pseudorandom numbers at a great rate, it may reduce contention for each thread to have its own pseudorandom-number generator.
-
- Returns:
- a pseudorandom
double
greater than or equal to 0.0
and less than 1.0
.
- See Also:
Random.nextDouble()