Skip to content

Arrays and Collection Framework

Büşra Oğuzoğlu edited this page Jul 4, 2022 · 31 revisions

Arrays and Collection Framework

1. Arrays:

Declaration:

type arrName[];
OR
type[] arrName;

Instantiation:

arrName = new type[size];

Can be combined in one statement:

type[] myArray = new type[size];

If elements are already known, declaration/instantiation can be done in the following way:

int[] nums = {1, 2, 1, 1, 3};

Accessing and Editing Elements:

String[] cities = {"Eskisehir", "Istanbul", "Izmir"};
System.out.println(cities[0]);

cities[0] = "Ankara";

2. Multidimensional Arrays:

Declaration and Instantiation:

Similar to a 1D array but adding more dimensions:

Syntax:

data_type[1st dimension][2nd dimension][]..[Nth dimension] 
array_name = new data_type[size1][size2]….[sizeN];

As an example:

int[][] intArray = new int[10][20]; //a 2D array or matrix
int[][][] intArray = new int[10][20][10]; //a 3D array

Same as 1D arrays, if the elements are known declaration can be done in the following manner: (R1C1 corresponds to row 1 column 1)

data_type[][] arrName = {
                        {valueR1C1, valueR1C2, ....}, 
                        {valueR2C1, valueR2C2, ....}
                        };

Accessing and Editing Elements:

We can use nested loops to add elements to a multi-dimensional array, as an example:

for (int i = 1; i <= 9; i++) {
       for (int j = 1; j <= 9; j++) {
            intArray[i][j] = i*j;
       }
}

3. ArrayList:

ArrayLists are dynamic, unlike arrays. This makes them easier to use when there will be lots of manipulations to the array (adding and deleting many elements)

ArrayList<Type> arrName = new ArrayList<Type>();

Accessing and Editing Elements:

Creating an Arraylist object of string type

ArrayList<String> myList = new ArrayList<>();

Adding elements

myList.add("First");

Adding to specific index

myList.add(1, "Second");

Setting element at specific index

myList.set(1, "Element two");

Removing element at specific index

myList.remove(1);

Removing specific element

myList.remove("First");

Get element at index

String new = myList.get(0);

4. LinkedList:

Linked list in collections framework is implemented as doubly linked list, this means that nodes contain pointers (data fields as references) to both next and previous node in the list. (Normally, linked list nodes only have references to next node as one of their data field.)

LinkedList<Type> linkedListName = new LinkedList<Type>();

Accessing and Editing Elements:

add and remove functions can be used in the same way as ArrayList. However, it is important to understand how a linked list works internally.

5. Stack and Queue:

6. Set (HashSet):

7. Map (HashMap):

Clone this wiki locally