简体   繁体   中英

Removing all occurrences of an int and returning new array

I'm trying to find all occurrences of an element in an array and returning a new array with the occurrences removed and the array being adjusted for any differences in size. For example I want to remove all occurrences of 4 from the array {1,2,3,4,4,4} and return just {1,2,3}.

This is the code i've written

public static int[] removeElement(int[] array, int element) {

    int j = 0;
    int k = 0;

    for (int i =0;i<array.length;i++){
        if (array[i]==element){
            j++;
        }
    }
    int[] newArray = new int[array.length-j];

    for (int i =0;i<array.length-j;i++){
        if(array[i]!=element){
            newArray[k]=array[i];
            k++;
        }
    }
    return newArray;

}

However I get a very weird output

[I@3a0b2771

Can anyone point me in the right direction as to where I've gone wrong?

What you are seeing is the array identity rather than its contents. This is the default output when you try to print something that doesn't override the toString() method. From the documentation:

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

 getClass().getName() + '@' + Integer.toHexString(hashCode())

In your case [I means that it is an int array.

There are a couple of ways you can print the array elements as you intend:

  • Use Arrays.toString() : Use this when printing a simple array. In your case it would be something like:

    System.out.println(Arrays.toString(newArray));

  • Use Arrays.deepToString() : You should use this when printing an array of arrays.

If you need to work with arrays, you should check the Arrays class documentation . It contains many methods for manipulating arrays that may be helpful.

You're directly printing an array to the screen elsewhere in your code. Print each element in a for loop, and you'll iterate over the entire new array to see the changes.

for(int i=0;i<newArray.length;i++) { 
    System.out.println(newArray[i]);
}

Using the [i] notation on an array will access the element held at this index, in this case the i'th integer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM