问题
I've just recently started with Java and have gotten to Arrays. from what I can tell there are two ways of creating Arrays.
The first method makes the most sense to me coming from a python background.
type[] ArrayName;
i.e.
int[] agesOfParticipants;
However a lot of resources online use a different method of creating arrays.
ArrayList<ArrayType> Name = new ArrayList<ArrayType>;
not only is this different but from what I can tell the term ArrayList is at least partially interchangeable depending on circumstance. For instance in this response ArrayList is replaced by class A, which is declared earlier.
A<String> obj=new A<String>();
Sorry if this is all basic stuff, but I can't find anywhere that really distinguishes between the two.
回答1:
In java objects are created using new
keyword
creating new
Integer
array with size10
, array consists of square brackets[]
Integer[] array = new Integer[10];
System.out.println(Arrays.toString(array)); // print array values `[..]`
creating
Integer
object with value 10
Integer object = new Integer(10);
System.out.println(object); // print object value 10
creating List that only holds
Integer
values
List<Integer> list = new ArrayList<>();
list.add(object);
System.out.println(object); // prints list with values [10]
Angular brackets
<>
are Generics, that are used to define homogeneous type of objects (for example list of Integers only)
来源:https://stackoverflow.com/questions/53983355/difference-between-using-angle-and-square-bracket-methods-in-creation-of-java-ar