我正在逐渐从 C 转向 java 编程。在这样做的同时,我在理解以下场景时感到困惑:
我有以下 Java 代码:
ArrayList<Integer> myList = new ArrayList<Integer>();
for(int j = 0 ; j < 10 ;j++){
myList.add(j);
}
System.out.println(myList);
the o/p is:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
根据我的理解,我这里有一个 ArrayList 类型的对象(myList)。
现在我尝试对 Array 对象执行相同的操作:相同的代码,但用 Array 替换 Arraylist:
int [] Arr = new int[]{1,2,3,4,5,6,7,8,9,10};
System.out.println(Arr);
我得到垃圾值。为什么会这样? Array 和 ArrayList 有什么区别?
与在 C 中一样,数组的名称有点像指针。 (它有第一个元素的地址),那么在 Java 中,对象的名称意味着什么?
地址或引用?
有什么不同?
为什么在 Array 和 ArrayList 的情况下我会得到不同的结果?
虽然问题的所有部分都在不同的帖子中得到了回答,但我想谈谈你的具体措辞。
首先,建议您将列表类型声明为接口(interface),并将其初始化为实现:
List<Object> list = new ArrayList<Object>();
List<Object> list = new ArrayList<>(); // JDK 7 or later allows you to omit the generic type.
您可以使用多个实现(ArrayList
、LinkedList
...)来实现List
接口(interface)。参见 the collection tutorial .
What is the difference between Array and ArrayList?
ArrayList
是一个类,参见 API .它用作 List
接口(interface) 的实现,参见 API .它们是 Java 集合框架的一部分。
数组不像ArrayList
那样是类,但数组和类的实例都是对象。小心大写 Array
,因为它是 different class .
I get garbage values. Why is this so?
Why do I get varied results in case of Array and ArrayList?
这与 println
方法有关。它会自动调用传递给它的参数的 toString
方法。 toString
方法是为 Object
类定义的,它是所有其他类的父类(super class),因此它们都继承它。除非子类覆盖继承的方法,否则它会保留其父类(super class)的实现。让我们看看它对 Object
做了什么:
public String toString()
Returns a string representation of the
object. In general, the toString method returns a string that
"textually represents" this object. The result should be a concise but
informative representation that is easy for a person to read. It is
recommended that all subclasses override this method.
The toString method for class Object returns a string consisting of the name of the
class of which the object is an instance, the at-sign character `@',
and the unsigned hexadecimal representation of the hash code of the
object. In other words, this method returns a string equal to the
value of:
getClass().getName() + '@' + Integer.toHexString(hashCode())
强调我的。如您所见,这就是打印数组变量时得到的“垃圾”。由于数组不是类,因此它们不能重写此方法(数组可以调用 Object
的所有方法,尽管它们不会以通常的方式将其子类化)。然而,Object
的子类 AbstractCollection
覆盖了这个:
public String toString()
Returns a string representation of this
collection. The string representation consists of a list of the
collection's elements in the order they are returned by its iterator,
enclosed in square brackets ("[]"). Adjacent elements are separated by
the characters ", " (comma and space). Elements are converted to
strings as by String.valueOf(Object).
由于 ArrayList
是 AbstractList
的子类,AbstractList
是 AbstractCollection
的子类(并且它们不会覆盖 toString
),你会得到“简洁但信息丰富的表示形式,易于人们阅读”。
关于 JVM 如何处理数组有一些细节,但为了从开发人员的角度理解输出,这就足够了。