Skip to content

Java tutorials #140

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
May 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,150 @@ sidebar_label: ArrayLists and Collections Framework
sidebar_position: 2
tags: [java, array-lists-and-collections-framework]
description: In this tutorial, you will learn about ArrayLists and the Collections Framework in Java.
---
---

# ArrayLists and the Collections Framework in Java

## Introduction

Java's Collections Framework provides a set of classes and interfaces for storing and manipulating groups of data as a single unit. `ArrayList` is one of the most commonly used classes in this framework, offering dynamic arrays that can grow and shrink in size.

## ArrayList

An `ArrayList` is a resizable array that provides more functionality and flexibility compared to a standard array. It is part of the `java.util` package.

### Declaration

To use `ArrayList`, you need to import it from the `java.util` package.

### Syntax

```java
import java.util.ArrayList;

ArrayList<dataType> arrayListName = new ArrayList<>();
```

### Example

```java
import java.util.ArrayList;

public class Main {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<>();

// Adding elements
names.add("Alice");
names.add("Bob");
names.add("Charlie");

// Accessing elements
System.out.println(names.get(0)); // Outputs: Alice

// Modifying elements
names.set(1, "Robert");

// Removing elements
names.remove(2);

// Iterating over the ArrayList
for (String name : names) {
System.out.println(name);
}
}
}
```

### Common Methods

- `add(element)`: Adds an element to the end of the list.
- `add(index, element)`: Inserts an element at the specified index.
- `get(index)`: Returns the element at the specified index.
- `set(index, element)`: Replaces the element at the specified index with the specified element.
- `remove(index)`: Removes the element at the specified index.
- `remove(element)`: Removes the first occurrence of the specified element.
- `size()`: Returns the number of elements in the list.
- `clear()`: Removes all elements from the list.
- `isEmpty()`: Returns `true` if the list contains no elements.

## Collections Framework

The Collections Framework provides a unified architecture for representing and manipulating collections. It includes interfaces, implementations, and algorithms.

### Interfaces

- `Collection`: The root interface for all collections.
- `List`: An ordered collection (also known as a sequence). `ArrayList` and `LinkedList` are its implementations.
- `Set`: A collection that contains no duplicate elements. `HashSet` and `TreeSet` are its implementations.
- `Queue`: A collection used to hold multiple elements prior to processing. `LinkedList` and `PriorityQueue` are its implementations.
- `Map`: An object that maps keys to values. `HashMap` and `TreeMap` are its implementations.

### Example: Using Different Collections

```java
import java.util.*;

public class Main {
public static void main(String[] args) {
// List example
List<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Orange");
System.out.println("List: " + list);

// Set example
Set<String> set = new HashSet<>();
set.add("Apple");
set.add("Banana");
set.add("Apple"); // Duplicate element will not be added
System.out.println("Set: " + set);

// Queue example
Queue<String> queue = new LinkedList<>();
queue.add("Apple");
queue.add("Banana");
queue.add("Orange");
System.out.println("Queue: " + queue);
System.out.println("Queue poll: " + queue.poll()); // Removes and returns the head of the queue

// Map example
Map<String, Integer> map = new HashMap<>();
map.put("Apple", 1);
map.put("Banana", 2);
map.put("Orange", 3);
System.out.println("Map: " + map);
System.out.println("Map get: " + map.get("Banana")); // Returns the value for the specified key
}
}
```

### Algorithms

The `Collections` class provides static methods that operate on collections, such as sorting and searching.

#### Example: Sorting a List

```java
import java.util.*;

public class Main {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("Banana");
list.add("Apple");
list.add("Orange");

Collections.sort(list); // Sorts the list in natural order
System.out.println("Sorted List: " + list);

Collections.sort(list, Collections.reverseOrder()); // Sorts the list in reverse order
System.out.println("Reverse Sorted List: " + list);
}
}
```

## Conclusion

The Collections Framework in Java provides a powerful and flexible set of classes and interfaces for managing groups of objects. `ArrayList` is a versatile and commonly used class within this framework. Understanding how to use `ArrayList` and other collections, as well as the algorithms provided by the `Collections` class, is crucial for effective Java programming.
159 changes: 158 additions & 1 deletion docs/java/arrays-and-collections/arrays-in-java.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,161 @@ sidebar_label: Arrays in Java
sidebar_position: 1
tags: [java, arrays, programming, java arrays]
description: In this tutorial, we will learn about arrays in Java. We will learn about what arrays are, how to declare and initialize arrays, how to access elements in an array, and how to use arrays in Java.
---
---

# Arrays in Java

## Introduction

Arrays in Java are used to store multiple values of the same type in a single variable, instead of declaring separate variables for each value. Arrays are a fundamental data structure that can help in organizing and managing data efficiently.

## Array Declaration

### Syntax

To declare an array, specify the data type followed by square brackets and the array name.

```java
dataType[] arrayName;
```

### Example

```java
int[] numbers;
String[] names;
```

## Array Initialization

### Static Initialization

You can initialize an array at the time of declaration with a set of values.

```java
int[] numbers = {1, 2, 3, 4, 5};
String[] names = {"Alice", "Bob", "Charlie"};
```

### Dynamic Initialization

You can also allocate memory for the array using the `new` keyword and then assign values to the array elements.

```java
int[] numbers = new int[5]; // Array of 5 integers
numbers[0] = 1;
numbers[1] = 2;
numbers[2] = 3;
numbers[3] = 4;
numbers[4] = 5;
```

## Accessing Array Elements

Array elements are accessed using their index, which starts from 0.

### Example

```java
int[] numbers = {1, 2, 3, 4, 5};
System.out.println(numbers[0]); // Outputs: 1
System.out.println(numbers[4]); // Outputs: 5
```

## Looping Through Arrays

### For Loop

You can use a `for` loop to iterate through all the elements of an array.

```java
int[] numbers = {1, 2, 3, 4, 5};
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
```

### Enhanced For Loop (For-Each Loop)

The enhanced `for` loop provides a simpler way to iterate through the elements of an array.

```java
int[] numbers = {1, 2, 3, 4, 5};
for (int number : numbers) {
System.out.println(number);
}
```

## Multi-Dimensional Arrays

Java supports multi-dimensional arrays, which are arrays of arrays.

### Two-Dimensional Array

#### Declaration and Initialization

```java
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
```

#### Accessing Elements

```java
System.out.println(matrix[0][0]); // Outputs: 1
System.out.println(matrix[2][2]); // Outputs: 9
```

#### Looping Through a Two-Dimensional Array

```java
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
```

### Example: Matrix Addition

```java
public class MatrixAddition {
public static void main(String[] args) {
int[][] matrix1 = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

int[][] matrix2 = {
{9, 8, 7},
{6, 5, 4},
{3, 2, 1}
};

int[][] sum = new int[3][3];

for (int i = 0; i < matrix1.length; i++) {
for (int j = 0; j < matrix1[i].length; j++) {
sum[i][j] = matrix1[i][j] + matrix2[i][j];
}
}

// Display the result
for (int[] row : sum) {
for (int element : row) {
System.out.print(element + " ");
}
System.out.println();
}
}
}
```

## Conclusion

Arrays are a powerful and essential feature in Java, allowing you to store and manage collections of data efficiently. Understanding how to declare, initialize, and manipulate arrays, as well as how to use multi-dimensional arrays, is crucial for effective Java programming.
Loading