Difference between using angle and square bracket methods in creation of Java Arrays

别来无恙 提交于 2021-02-16 20:16:05

问题


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 size 10, 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!