Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

arrays

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.

like image 929
corvus_poe Avatar asked Jun 13 '26 22:06

corvus_poe


1 Answers

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)

like image 55
Deadpool Avatar answered Jun 16 '26 01:06

Deadpool