Как найти количество элементов массива java

В Java у массивов есть свойство length, которое содержит его длину. Это
свойство доступно только для чтения и позволяет узнать количество элементов в
одномерном массиве.

Object[] array = { ... };
System.out.println(array.length);

Чтобы выяснить количество элементов в двумерном массиве в Java 8 предлагается
воспользоваться интерфейсом потоков.

Object[][] array = { ... };
int count = Stream.of(array).mapToInt(m -> m.length).sum();
System.out.println(count);

В более ранних версиях придётся устраивать цикл, в котором суммируются длины
всех подмассивов в переданном аргументе.

public static int count(Object[][] array) {
    int result = 0;
    for (Object[] m : array) {
        result += m.length;
    }
    return result;
}

Стоит заметить, что для вычисления длины строки используется метод length,
не свойство (т.е. нужно писать скобочки), а для вычисления длины любой коллекции
применяется метод size.

String s = "...";
System.out.println(s.length());

Set<Integer> s = new TreeSet<Integer>();
s.add(...);
System.out.println(s.size());

Say i have the array

int theArray = new int[20];

The length of the array is 20 but the count is 0. How can i get the count?

Alex Kulinkovich's user avatar

asked Dec 14, 2010 at 15:56

El Fuser's user avatar

1

What do you mean by “the count”? The number of elements with a non-zero value? You’d just have to count them.

There’s no distinction between that array and one which has explicitly been set with zero values. For example, these arrays are indistinguishable:

int[] x = { 0, 0, 0 };
int[] y = new int[3];

Arrays in Java always have a fixed size – accessed via the length field. There’s no concept of “the amount of the array currently in use”.

answered Dec 14, 2010 at 15:58

Jon Skeet's user avatar

Jon SkeetJon Skeet

1.4m859 gold badges9092 silver badges9165 bronze badges

5

Iterate through it and count the elements which aren’t null:

int counter = 0;
for (int i = 0; i < theArray.length; i ++)
    if (theArray[i] != null)
        counter ++;

This can be neatened up by using for:each loops and suchlike, but this is the jist.

Either that, or keep a counter and whenever you add an element, increment it.

answered Dec 14, 2010 at 16:00

TartanLlama's user avatar

TartanLlamaTartanLlama

63.3k13 gold badges155 silver badges193 bronze badges

What I think you may want is an ArrayList<Integer> instead of an array. This will allow you do to:

ArrayList<Integer> arr = new ArrayList<Integer>(20);
System.out.println(arr.size());

The output will be 0.

Then, you can add things to the list, and it will keep track of the count for you. (It will also grow the size of the backing storage as you need as well.)

Gopi's user avatar

Gopi

10k4 gold badges31 silver badges45 bronze badges

answered Dec 14, 2010 at 16:00

jjnguy's user avatar

jjnguyjjnguy

136k53 gold badges294 silver badges323 bronze badges

  1. Your code won’t compile, it should be int [] theArray = new int[20];;
  2. You can get the array length as theArray.length;
  3. For primitive types, the array will be initialized with the default values (0 for int).
  4. You can make it Integer [] theArray = new Integer[20]; and then count initialized members as this code does:

    public int count(Object [] array) {
        int c = 0;
        for(Object el: array) { if(el != null) c++; }
            return c;
    }
    

Please note that this answer isn’t about why you may need this and what is the best way to do what you want.

Gilad Green's user avatar

Gilad Green

36.6k7 gold badges59 silver badges95 bronze badges

answered Dec 14, 2010 at 16:04

khachik's user avatar

khachikkhachik

27.9k9 gold badges59 silver badges92 bronze badges

Java doesn’t have the concept of a “count” of the used elements in an array.

To get this, Java uses an ArrayList. The List is implemented on top of an array which gets resized whenever the JVM decides it’s not big enough (or sometimes when it is too big).

To get the count, you use mylist.size() to ensure a capacity (the underlying array backing) you use mylist.ensureCapacity(20). To get rid of the extra capacity, you use mylist.trimToSize().

answered Dec 14, 2010 at 16:01

Edwin Buck's user avatar

Edwin BuckEdwin Buck

69k7 gold badges99 silver badges135 bronze badges

There is no built-in functionality for this. This count is in its whole user-specific. Maintain a counter or whatever.

answered Dec 14, 2010 at 15:58

Petar Minchev's user avatar

Petar MinchevPetar Minchev

46.7k11 gold badges103 silver badges119 bronze badges

When defining an array, you are setting aside a block of memory to hold all the items you want to have in the array.

This will have a default value, depending on the type of the array member types.

What you can’t do is find out the number of items that you have populated, except for tracking it in your own code.

answered Dec 14, 2010 at 15:59

Oded's user avatar

OdedOded

488k99 gold badges880 silver badges1005 bronze badges

You can use a for each loop and count the number of integer values that are significant. You could also use an ArrayList which will keep track of the couny for you. Everytime you add or remove objects from the list it will automatically update the count. Calling the size() method will give you the current number of elements.

answered Dec 14, 2010 at 16:02

prgmast3r's user avatar

prgmast3rprgmast3r

4134 silver badges8 bronze badges

If you wish to have an Array in which you will not be allocating all of the elements, you will have to do your own bookkeeping to ensure how many elements you have placed in it via some other variable. If you’d like to avoid doing this while also getting an “Array” that can grow capacities after its initial instantiation, you can create an ArrayList

ArrayList<Integer> theArray = new ArrayList<Integer>();
theArray.add(5); // places at index 0
theArray.size(); // returns length of 1
int answer = theArray.get(0); // index 0 = 5

Don’t forget to import it at the top of the file:

import java.util.ArrayList;

answered Dec 14, 2010 at 16:04

adimitri's user avatar

adimitriadimitri

1,2969 silver badges13 bronze badges

If you assume that 0 is not a valid item in the array then the following code should work:

   public static void main( String[] args )
   {
      int[] theArray = new int[20];
      theArray[0] = 1;
      theArray[1] = 2;

      System.out.println(count(theArray));
   }

   private static int count(int[] array) 
   {
      int count = 0;
      for(int i : array)
      {
         if(i > 0)
         {
            count++;
         }
      }
      return count;
   }

answered Dec 14, 2010 at 16:04

Brent Wilson's user avatar

You can declare an array of booleans with the same length of your array:

true: is used
false: is not used

and change the value of the same cell number to true. Then you can count how many cells are used by using a for loop.

answered Oct 18, 2018 at 4:01

Ali Tohidi's user avatar

You could also make it an Integer array. That way each item will be null. Then just count the number of non-null values. This still allows you to add ints, like you could before since Java does autoboxing and unboxing of primitives and their wrappers.

Integer[] numbers = new Integer[30];

int count = 0;
for (Integer num : numbers)
    if (num != null) count++;

System.out.println(count);

answered Feb 2, 2022 at 4:33

tazboy's user avatar

tazboytazboy

1,6535 gold badges21 silver badges39 bronze badges

Isn’t it just: System.out.println(Array.length);? Because this is what it seems like you are looking for.

blalasaadri's user avatar

blalasaadri

5,9705 gold badges38 silver badges58 bronze badges

answered Dec 9, 2014 at 10:47

uffes's user avatar

int theArray[] = new int[20];
System.out.println(theArray.length);

answered Dec 14, 2010 at 15:58

Ram's user avatar

2

Table of contents

      • Java Array Length: How do you find the length of an array?
      • Searching a value using Array Length in Java
      • Searching for the lowest value in the array
      • Searching for the highest value in the array
      • Frequently Asked Questions
      • Conclusion
  1. Java Array Length: How do you find the length of an array?
  2. Searching a value using Array Length in Java
  3. Searching for the lowest value in the array
  4. Searching for the highest value in the array
  5. Frequently Asked Questions
  6. Conclusion

Java Array Length: How do you find the length of an array?

The length attribute of Java holds the number of elements in the array. In Java, there is no predefined method by which you can find the length of an array. But you can use the length attribute to find the length of an array. When we declare an array, the total number of elements in it is called the array’s length, or we can also call it the size of the array. You can also take up a java programming free online course and learn more about the concepts before learning about arrays in java.

Let us see the below example for a better understanding:

int len = thisArray.length;

Let us see a program using the Array Length attribute of Java:

import java.util.*;
class Main
{
    public static void main(String[] args)
    {
        Integer[] intArray = {1,3,5,7}; //integer array
        String[] strArray = { "one", "two", "three", “four” }; //string array
 
                //print each array and their corresponding length
        System.out.println("Contents of Integer Array : " + Arrays.toString(intArray));
        System.out.println("The length of the array is : " + intArray.length);
 
        System.out.println("Contents of String array : " + Arrays.toString(strArray));
        System.out.println("The length of the String array is : " + strArray.length);
    }
}

OUTPUT:

Contents of Integer Array: [1,2,5,7]

The length of the array is: 4

Contents of String array: [one, two, three, four]

The length of the String array is: 4

In the above program, the length function counts the total number of elements in the array, whether a string or a number. The length attribute takes the length of the array. There can be different scenarios where you can use the Array Length attribute, such as:

  • To search for a minimum value in the array.
  • To find the maximum number in an array.
  • To get any specific value from the array. 
  • To check if any specific value is there in the array or not.

There can be more scenarios where you can use the Array Length attribute in Java. 

In this article, we will see more scenarios of using the Array Length attribute of Java with some useful programs and examples. 

Searching a value using Array Length in Java

The Array Length attribute can be used for several cases, so it is essential. It can also be used for searching for a value in an array. You need to use a loop that will iterate through all the elements in the array one after the other until it finds the searched element. 

When the code runs, the loop will start searching the element in the array until it reaches the last element or traverses the complete length of the array. When it is traversing through each element in the array, it compares the value of each element to the value to be searched, and if the value of the element is matched, then it stops the loop.

The program below does the same we just discussed, and it will help you to understand better how the code will work:

import java.util.*;
class Main{
public static void main(String[] args) {
    String[] strArray = { “HTML”, “CSS”, "Java", "Python", "C++", "Scala", }; //array of strings
                //search for a string using searchValue function
    System.out.println(searchValue(strArray, "C++")?" value C++ found":"value C++ not found");
    System.out.println(searchValue(strArray, "Python")?"value Python found":"value Python not found");
}
 
private static boolean findValue(String[] searchArray, String lookup)
{
    if (searchArray != null) {
        int arrayLength = searchArray.length; //computes the array length
        for (int i = 0; i <= arrayLength - 1; i++)
        {
            String value = searchArray[i]; //searching for value using for loop
            if (value.equals(lookup)) {
               return true;
            }
        }
    }
return false;
}

Value C++ found

Value Python found

In the above program, as you can see, we have an array that contains the names of some programming languages. There’s a function with the name ‘findValue’ that searches for the specific value we are trying to find in the array. We used the for loop that traverses through each element in the array and finds it the value exists in our array or not. We gave two statements for both the cases, such as if the value is in the array or not. What it does is it returns true if the value is found in the array and false otherwise. 

In our case, the values C++ and Python were there in our array and that’s the reason it returned true or the statements that we provided as true. 

Searching for the lowest value in the array

As we have seen, how the Array length attribute works and how it makes our code easier to find the value we are searching for. In this section, we will see how we can find the minimum value in an array. 

The below program is used to find the lowest value in an array:

import java.util.*;
class Main {
    public static void main(String[] args) {
       int[] intArray = { 2,40,11,10,3,44 }; //int array
       System.out.println("The given array:" + Arrays.toString(intArray));
       int min_Val = intArray[0]; // we are assigning first element to min value
       int length = intArray.length;
       for (int i = 1; i <= length - 1; i++) // it goes till end of array, compares with each element and finds the minimum value
        {
            int value = intArray[i];
            if (value <min_Val) {
               min_Val = value;
            }
        }
 
    System.out.println("The lowest value in the array: "+min_Val);
    }
}

OUTPUT:

The given array: [2, 40, 11, 10, 3, 44]

The lowest value in the array: 2

We gave the first element as the lowest element in the array in the above program. But still, it assigned the first element 2 as the minimum value and compared it with other elements in the array. When it is found that the value 2 is the only minimum, it comes out from the loop and returns the min value from the array. 

Suppose we have provided the minimum value at some other place in the array. In that case, it will assign each value in the array as a minimum value and compare it with other elements until it finds the correct one. This way, we can find the minimum value in the array.

Searching for the highest value in the array

In the above section, we saw how to find the minimum value in an array. The same logic will be applied in this example, where we search for the maximum value in an array. The only thing that will change is only the smaller than (<) sign. 

Let us see the example below:

import java.util.*;
class Main {
   public static void main(String[] args) {
        int[] intArray = { 2,40,1,10,95,24 }; //int array
        System.out.println("The given array:" + Arrays.toString(intArray));
        int max_Val = intArray[0]; //reference element as maximum value
        int length = intArray.length;
        for (int i = 1; i <= length - 1; i++) // It finds the maximum value of the element by comparing others to reference
        {
        int value = intArray[i];
        if (value >max_Val) {
             max_Val = value;
            }
        }
       System.out.println("The largest value in the array: "+max_Val);
    }
}

OUTPUT:

The given array: [2,40,1, 10,95,24]

The largest value in the array: 95

The above code did the same as it did to find the smallest value in the array. The thing that is changed is the condition for comparing with another element. We compared the smallest elements, and now we used to find the largest ones. 

Frequently Asked Questions

Q. What is the difference between the Size of ArrayList and the length of an Array?

A. In the ArrayList attribute, there is no length property, but it still gives the length by using the size() method, whereas the length property of the array gives the total number of elements in the array or the length of the array. 

Q. Are length and length() same in Java?

A. Length() is a method used for the string objects to return the number of characters in a string where ‘length’ is the property to find the total number of elements in an array, and it returns the size of the array. 

Q. How to find the largest number in an array using the array length attribute in Java?

A. To find the largest number or value in an array, we need to create a loop that will traverse through each element in the array and compares each element by assigning the first value of the array as the maximum. To understand better, go to the section ‘Searching for the highest value in the array’ of this article, where we discussed an example. 

Q. How to get the length in Java?

A. There are different scenarios to find the length. For example, we have two options to use the length() method or the java length attribute. Both of them are used for different purposes and return different values. So, if you want to find the length of characters in a string, you need to use the length() method, whereas if you want to find the length or size of an array, you must use the length attribute of Java. 

Q. What do you mean by length function in Java?

A. The length() function in Java is used to get the number of characters in a string. 

Conclusion

Thus, we have come to the end of this article where we discussed the Java Array Length attribute, which is very useful in different programming scenarios. We also discussed specific cases, such as finding the largest and smallest value in an array. However, there are more uses for this attribute. So, we encourage you to find more cases and try to use this length attribute. 

In this blog post, we are going to learn an important topic pertaining to Java i.e Array length.

Java is a high-end programming language by accompanying robustness, security, and greater performance.

An array length in Java represents a series of elements that an array could really hold. There really is no predetermined method for determining an object’s length. In Java, developers can discover its array length with the help of array attribute length. One such attribute is used in conjunction with array names. To gain deeper insights into this programming language, java training is compulsory. Therefore in this blog post, we’ll look at how to calculate the size as well as the length of the arrays in Java.

Length Attribute in Java

The length attribute throughout Java represents the size of the array. Each array has a length property, for which the value seems to be the array’s size. The overall quantity of elements that the array can encompass is denoted by its size. In order to access the length property, use dot (.) operator which is accompanied by an array name. Also we can determine the length of int[ ]double[] and  String[]. As an example:

int[] arr=new int[5];  

int arrayLength=arr.length

In the above sample code, arr represents the array type and it is the int with a capacity of 5 elements. In simple terms array Length perhaps is the variable that keeps track of the length of an array. An array name (arr) is accompanied by a dot operator as well as the length attribute to determine the length of the array. It defines the array’s size.

Array length = Array’s last Index+1

Array Length in Java with Examples

Array last index = 7

Array length = 7+1 = 8

It is important to note that such length of the array defines the upper limit number of the elements that can hold or its capacity. This does not include the elements which are added to the array. It is, length comes back the array’s total size. The length and size of arrays for whom the elements have been configured just at the time of their establishment were the same.

However, if we’re talking well about an array’s logical size or index, after which merely int arrayLength=arr.length-1, since an array index begins at 0. As a result, the logical, as well as an array index, was always one less than the real size.

First Index:

0 1 2 3 4 5 6 7 8 9

In the above picture, 0 is the first index and the array length will be 10.

Now we will explore how to fetch the length of an array using an example.

Arraylengthex1.java

public class ArrayLengthExample1

{

    public static void main(String[] args)

    {

        //defining an array of type int named num

        //the square bracket contain the length of an array

        int[] num = new int[11];

        //length is an Array attribute that determines the array length

        int arrayLength=num.length;

        //prints array length

        System.out.println(“length of an array is “+ arrayLength);

    }

}

Output:

length of an array is 11

Arraylenghtex2.java

public class ArrayLengthExample2 {

    public static void main(String[] args) {

        //initializing an array of type String named country

        String[] country = { “cat”, “dog”, “pig”, “mouse”, };

        //length is an Array attribute that determines the array length

        int arrayLength=country.length;

        //prints array length

        System.out.println(“Size of an array is: “ + arrayLength);

    }

}

Output:

Size of an array is 4

ArraylengthEx3.java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

public class ArrayLengthEx3 {

    private static void LengthOfArray(String[] array) {

        //checks array is empty or not

        if (array == null)

        {

            //if the array is empty prints the following statement

            System.out.println(“an array length cannot be empty.”);

        }

        else {

            //length attribute of the Array class determines the length of an array

            int arrayLength = array.length;

            //prints the array length

            System.out.println(“An array length is: “+arrayLength);

        }

    }

    public static void main(String[] args) {

        String[] fruits = { “Banana”, “Apple”, “Melon”, };

        String[] alphabets = { “k”, “t”, “l”, “m”, };

        String[] numbers = { “25”, “63”, “84”, “90”, “11”, };

        //passing null value to the function

        LengthOfArray(null);

        //passing fruits array to the function

        LengthOfArray(fruits);

        //passing alphabets array to the functiona

        LengthOfArray(alphabets);

        //passing numbers array to the function

        LengthOfArray(numbers);

    }

}

Output:

an array length cannot be empty.
An array length is: 3
An array length is: 4
An array length is: 5

Searching a Value Using the Array Length in Java

The array length does have a lot of good properties which can be used in coding. In the following scenario, we just use the length of an array to loop through all elements and see if the specified value is visible.

Example:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

public class ArrayLengthJava {

    private static boolean arrayContainsValue(String[] myArray,

    String lookForValue) {

        if (myArray != null) {

            int arrayLength = myArray.length;

            for (int i = 0; i <= arrayLength 1; i++) {

                String value = myArray[i];

                if (value.equals(lookForValue)) {

                    return true;

                }

            }

        }

        return false;

    }

    public static void main(String[] args) {

        String[] JavaArray = { “I”, “hate”, “sweets”};

        System.out.println(arrayContainsValue(JavaArray, “hate”));

        System.out.println(arrayContainsValue(JavaArray, “love”));

    }

}

Output:

true
false

The program above returns true because “hate” is present in the array, but “love” is a non-existent element, so the result is false.

Search for the Lowest Value in the Array

The length of an array can be used to find the lowest value in an array object.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

public class ArrayLengthJava {

    private static int minValue(int[] myArray) {

        int minValue = myArray[0];

        int arrayLength = myArray.length;

        for (int i = 1; i <= arrayLength 1; i++) {

            int value = myArray[i];

            if (value < minValue) {

                minValue = value;

            }

        }

        return minValue;

    }

    public static void main(String[] args) {

        int[] JavaArray = { 28, 46, 69, 50 };

        System.out.println(“The min value in the array is: “+minValue(JavaArray));

    }

}

Output:

The minimum value in an array is: 28

Search for the Max Value in an Array

Moreover, we could use an array’s length to find the highest value in an array object.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

public class ArrayLengthJava {

    private static int maxValue(int[] myArray) {

        int maxValue = myArray[0];

        int arrayLength = myArray.length;

        for (int i = 1; i <= arrayLength 1; i++) {

            int value = myArray[i];

            if (value > maxValue) {

                maxValue = value;

            }

        }

        return maxValue;

    }

    public static void main(String[] args) {

        int[] JavaArray = { 29, 46, 85, 69 };

        System.out.println(“The max value in an array is: “+maxValue(JavaArray));

    }

}

Output:

The max value in an array is: 85

Conclusion

Hope you have got enough knowledge in handling array length in java. If you have any queries please drop them in the comments section to get them clarified.

Happy Coding!

Author Bio:

I am VarshaDutta Dusa, Working as a Senior Digital Marketing professional & Content writer in HKR Trainings. I Have good experience in handling technical content writing and aspire to learn new things to grow professionally. I am expertise in delivering content on the market demanding technologies like mulesoft Training, Dell Boomi Tutorial, Elasticsearch Course, Fortinet Course, postgresql Training, splunk, Success Factor, Denodo, etc.

In Java, the array length is the number of elements that an array can holds. There is no predefined method to obtain the length of an array. We can find the array length in Java by using the array attribute length. We use this attribute with the array name. In this section, we will learn how to find the length or size of an array in Java.

Array length Attribute

Java provides an attribute length that determines the length of an array. Every array has an in-built length property whose value is the size of the array. Size implies the total number of elements that an array can contain. The length property can be invoked by using the dot (.) operator followed by the array name. We can find the length of int[], double[], String[], etc. For example:

In the above code snippet, arr is an array of type int that can hold 5 elements. The arrayLength is a variable that stores the length of an array. To find the length of the array, we have used array name (arr) followed by the dot operator and length attribute, respectively. It determines the size of the array.

How to Find Array Length in Java

Note that length determines the maximum number of elements that the array can contain or the capacity of the array. It does not count the elements that are inserted into the array. That is, length returns the total size of the array. For arrays whose elements are initialized at the time of its creation, length and size are the same.

If we talk about the logical size, the index of the array, then simply int arrayLength=arr.length-1, because the array index starts from 0. So, the logical or array index will always be less than the actual size by 1.

How to Find Array Length in Java

Let’s find the length of the array through an example.

ArrayLengthExample1.java

Output:

The length of the array is: 10

ArrayLengthExample2.java

Output:

The size of the array is: 7

ArrayLengthExample3.java

Output:

The array is empty, can't be determined length.
The length of the array is: 6
The length of the array is: 5
The length of the array is: 7

Добавить комментарий