什么是空?
null是任何东西的实例吗?
null属于哪个集合?
它在内存中是如何表示的?
什么是空?
null是任何东西的实例吗?
null属于哪个集合?
它在内存中是如何表示的?
当前回答
Null是一个特殊值,它不是任何东西的实例。很明显,它不能是任何东西的实例。
其他回答
An interesting way to see null in java in my opinion is to see it as something that DOES NOT denote an absence of information but simply as a literal value that can be assigned to a reference of any type. If you think about it if it denoted absence of information then for a1==a2 to be true doesn't make sense (in case they were both assigned a value of null) as they could really could be pointing to ANY object (we simply don't know what objects they should be pointing to)... By the way null == null returns true in java. If java e.g. would be like SQL:1999 then null==null would return unknown (a boolean value in SQL:1999 can take three values : true,false and unknown but in practise unknown is implemented as null in real systems)... http://en.wikipedia.org/wiki/SQL
Null是一个特殊值,它不是任何类的实例。下面的程序说明了这一点:
public class X {
void f(Object o)
{
System.out.println(o instanceof String); // Output is "false"
}
public static void main(String[] args) {
new X().f(null);
}
}
Java中的null类似于c++中的nullptr。
c++程序:
class Point
{
private:
int x;
int y;
public:
Point(int ix, int iy)
{
x = ix;
y = iy;
}
void print() { std::cout << '(' << x << ',' << y << ')'; }
};
int main()
{
Point* p = new Point(3,5);
if (p != nullptr)
{
p->print();
p = nullptr;
}
else
{
std::cout << "p is null" << std::endl;
}
return 0;
}
Java中的相同程序:
public class Point {
private int x;
private int y;
public Point(int ix, int iy) {
x = ix;
y = iy;
}
public void print() { System.out.print("(" + x + "," + y + ")"); }
}
class Program
{
public static void main(String[] args) {
Point p = new Point(3,5);
if (p != null)
{
p.print();
p = null;
}
else
{
System.out.println("p is null");
}
}
}
现在你从上面的代码中明白什么是Java中的空了吗?如果没有,那么我建议你学习C/ c++中的指针,然后你就会明白。
注意,在C语言中,与c++不同,nullptr是未定义的,但使用NULL代替,这也可以在c++中使用,但在c++中nullptr比NULL更可取,因为C语言中的NULL总是与指针相关,所以在c++中,后缀“ptr”被附加在单词的末尾,而且所有字母现在都是小写的,但这并不重要。
在Java中,每一个类非原语类型的变量都是对该类型或继承的对象的引用,null是空类对象引用,但不是空指针,因为在Java中没有“指针”这样的东西,而是使用对类对象的引用,Java中的null与类对象引用有关,所以你也可以称它为“nullref”或“nullrefobj”,但这很长,所以就叫它“null”。
在c++中,你可以为可选成员/变量使用指针和nullptr值,即没有值的成员/变量,如果它没有值,那么它等于nullptr,所以在Java中如何使用null例如。
字节码表示
Java的null有直接的JVM支持:使用三个指令来实现它:
aconst_null:例如,将一个变量设置为null,如Object o = null; Ifnull和ifnonnull:例如,if (o == null)将对象与null进行比较
第6章“Java虚拟机指令集”接着提到了null对其他指令的影响:它会对许多指令抛出NullPointerException异常。
2.4. “引用类型和值”在通用术语中也提到了null:
引用值也可以是特殊的空引用,即不指向任何对象的引用,这里用null表示。空引用最初没有运行时类型,但可以转换为任何类型。引用类型的默认值是null。
null关键字是一个表示空引用的文字,它不引用任何对象。Null是引用类型变量的默认值。
也可以看看
null: Java术语