قالب وردپرس درنا توس
Home / Tips and Tricks / How to create a matrix in Java

How to create a matrix in Java



How to use arrays in Java

An array in Java is a type of variable that can store multiple values. It stores these values ​​based on a key that can be used to look up that information.

Arrays can be useful for developers to store, organize and retrieve large amounts of data. Whether you keep track of high scores in a computer game or store client information in a database, a matrix is ​​often the best choice.

Also read: How to use matrices in Python

So, how do you create a matrix in Java? It all depends on the type of array you want to use!

How to create a matrix in Java

The word “array” is defined as a data structure, consisting of a collection of elements. These elements must be identified by at least one “index” or “key”.

There are therefore several data objects in Java that we can describe as arrays. We refer to the first as the “Java array.” Although it does make things a little more confusing, it’s actually more like what we would call a “list” in many other programming languages!

This is the simplest way to think of a Java array: as a list of sequential values. Here, a key is automatically assigned to each value in the sequence based on its relative position. The first index is always “0” and from there the number will increase step by step for each new object.

Unlike a list in say Python, however, Java matrices have a fixed size. There is no way to remove elements or add to the matrix while driving. This limitation is excellent for optimized code but of course has some limitations.

To create this type of matrix in Java, you simply create a new variable of your chosen data type with square brackets to indicate that it really is a matrix. We then enter each value in curly brackets, separated by commas. Values ​​are then reached using the index based on the order in this list.

String listOfFruit[] = {"apple", "orange", "lemon", "pear", "grape"};
System.out.println(listOfFruit[2]);

Although it is not possible to resize a Java array, we can change specific values:

listOfFruit[3] = “melon”;

ArrayLists

If you need to use modifiable Java matrices, you can select ArrayList. An ArrayList is not as fast, but it gives you more flexibility when driving.

To create a matrix list, you must initialize it with the selected data type, and then we can add each element individually using the add-in method. We also need to import ArrayList from the Java.util package.

import java.util.ArrayList;

class Main {

  public static void main(String[] args) {

    ArrayList arrayListOfFruit = new ArrayList();
    arrayListOfFruit.add("Apple");
    arrayListOfFruit.add("Orange");
    arrayListOfFruit.add("Mango");
    arrayListOfFruit.add("Banana");
    System.out.println(arrayListOfFruit);

  }

}

Now, at any time in our code, we will be able to add and remove elements. But remember that this will change the positions of all other values ​​and their respective keys. Thus I would do this:

System.out.println(arrayListOfFruit.get(3));
arrayListOfFruit.add(2, "Lemon");
System.out.println(arrayListOfFruit.get(3));

I would get a different printout every time I printed. Note that we use “get” to return values ​​at specific indices, and that I can add values ​​at different positions by passing my index as the first argument.

How to create a matrix in Java using maps

Another type of array in Java is the map. A map is an associative matrix that uses key / value pairs that do not change.

For example, this is a perfect way to store phone numbers. Here you can use the numbers as values ​​and the names of the contacts as indexes. So “197701289321” could have the key “Jeff.” This makes it much easier for us to quickly find the data we need, even when we add and remove data from our list!

We do it like this:

import java.util.HashMap;
import java.util.Map;

    Map phoneBook = new HashMap();
    phoneBook.put("Adam", "229901239");
    phoneBook.put("Fred", "981231999");
    phoneBook.put("Dave", "123879122");
    System.out.println("Adam's Number: " + phoneBook.get("Adam"));

As you can see then a Java Array is always an array, but an array is not always a Java Array!

How to use the multidimensional matrix in Java

The head is not spinning enough yet? Then take a look at the multidimensional matrix in Java!

This is a type of Java Array that has two “columns”.

Imagine that your typical Java array is an Excel spreadsheet. If so, you would have created a table with only a single column. We can consider it a “one-dimensional” database by changing data only from top to bottom. We have as many lines as we want (1st dimension) but only one column (the hypothetical 2nd dimension).

To add more columns, we simply add a second set of square brackets. We then fill in the rows and columns. The resulting data structure can be seen as an “array of arrays”, where each element is a whole array in itself!

In this example, we use integers (integers):

int[][] twoDimensions = {
      {1, 2, 3, 4},
      {5, 6, 7, 8},
      {9, 10, 11, 12},
};

But we can actually take this idea even further by creating a three-dimensional matrix! This would be one matrix with 2D matrices. You would build it like this:

int[][][] threeDimensions = {
        {
          {1, 2, 3},
          {4, 5, 6}
        },
        {
          {-1, -2, -3},
          {-4, -5. -61},
        }
};

Although this idea is tricky to conceptualize, try to imagine a database that has three axes, with cells moving in each direction.

So this is how you create a matrix in Java! While many who read this will never have to worry about three-dimensional matrices, it just shows how powerful and adaptable Java really is.

In fact, the list of things you can do with Java is unlimited. Like Array List. Why not continue your education with one of the best resources for learning Java?


Source link