📜  Java中数组和集合的区别

📅  最后修改于: 2022-05-13 01:55:15.939000             🧑  作者: Mango

Java中数组和集合的区别

Java中的数组是一组由通用名称引用的类似类型的变量。 Java中的数组的工作方式与 C/C++ 中的不同。以下是有关Java数组的一些要点。另一方面,任何表示为单个单元的单个对象组都称为对象的集合。在Java中,JDK 1.2 中定义了一个名为“集合框架”的单独框架,其中包含所有集合类和接口。

处理Collection最重要的是对Collection框架有超强的掌握,如下图所示:

例子

Java
// Java Program to Illustrate Difference
// Between Arrays and Collection
 
// Importing required classes
import java.util.*;
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Arrays
        String[] gfg
            = new String[] { "G", "E", "E", "K", "S" };
 
        // Trying printing the above array
        System.out.print(gfg);
 
        // New Line
        System.out.println();
 
        // Collection
        // Let us arbitarly create an empty ArrayList
        // of string type
        ArrayList al = new ArrayList();
 
        // Adding elements to above List
        // using add() method
        al.add("g");
        al.add("e");
        al.add("e");
        al.add("k");
        al.add("s");
 
        // Printing all elements of Collection (ArrayList)
        System.out.println(al);
    }
}


输出
[Ljava.lang.String;@3d075dc0
[g, e, e, k, s]

现在在了解了数组和集合之后,现在让我们将它们之间的区别列成表格,如下所示:

ArraysCollection
Arrays are fixed in size that is once we create an array we can not increased or decreased based on our requirement.Collection are growable in nature that is based on our requirement. We can increase or decrease of size.
With respect to memory Arrays are not recommended to use.With respect to memory collection are recommended to use.
With respect to performance Arrays are recommended to use.With respect to performance collection are not recommended to use.
Arrays can hold only homogeneous data types elements.Collection can hold both homogeneous and and heterogeneous elements.
There is no underlying data structure for arrays and hence ready made  method support is not available.Every collection class is implemented based on some standard data structure and hence for every requirement ready made method support is available being a performance. we can use these method directly and We are not responsible to implement these methods.
Arrays can hold both object and primitive.Collection can hold only object types but not primitive datatypes such as int, long, short, etc.