How to determine whether a 0 element in the int array is the default value or an assigned value?

problem:

In Java, the int array is initialized to 0 by default. So for a 0 element in the array, how to judge whether it is the default value or the assigned value? For example, in the following situation, it is impossible to distinguish whether the 0 of a[3] is assigned or the default; but if we want to insert an element at the end of the effective number of the array , how to find the end?

int[] a=new int[6] ;
a[0]= 1;
a[1]=0;
a[2]=3;
a[3]=0;

test:

System.out.println(a.length);
System.out.println(Arrays.toString(a));

Output

6
[1, 0, 3, 0, 0, 0]

in conclusion:

Although we only assigned the first 4 elements, the output is 6. This is because:

  1. What you get with a.length is not the number of valid digits, but the size of the array specified in new;
  2. Using Arrays.toString(a) is to output a[6] into a string;

So how do we find the end position of the valid data in the array?

Solution:

 1. Set an int variable to count the number of significant digits. When assigning a value to an array element, count++; or set a Boolean array, and set the Boolean value of the corresponding subscript to true for every assignment to an array element. In this way, there is a basis for finding the end of the valid data in the array.
 2. In fact, we can completely avoid this judgment of zero nature. As long as it is initialized at the same time when the array is declared, the [ ]size of the array is not filled in. In this way, it is easy to find the end of the array, expand the capacity first, and then add elements. Such as:

import java.util.Arrays;
public class Test_0 {
    
    
	public static void main(String[] args) {
    
    
		int[] a={
    
    1,0,3,0};
		//扩容
		a=Arrays.copyOf(a, a.length+1);//原数组为a;新数组空间大小为a.length+1;  将原数组复制完返回给新数组a)  新数组和原数组同名但不同地址 
		//找到末尾,然后插入一个元素
		a[a.length-1]=7;
		System.out.println(Arrays.toString(a));	
	}
}

Output:

[1, 0, 3, 0, 7]

Remarks:

Array expansion related source code:

  public static int[] copyOf(int[] original, int newLength) {
    
    
        int[] copy = new int[newLength];
        System.arraycopy(original, 0, copy, 0,
                         Math.min(original.length, newLength));
        return copy;
    }
 public static native void arraycopy(Object src,  int  srcPos,
                                        Object dest, int destPos,
                                        int length);

Guess you like

Origin blog.csdn.net/qq_41571459/article/details/113067310