Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Im trying to filter out any duplicate arrays that are passed through and return

ID: 3565747 • Letter: I

Question

Im trying to filter out any duplicate arrays that are passed through and return an array of only uniqe arrays that dont have any duplicates. Here is my code so far. (I am only allowed to use ARRAYS. I cant use Arraylist or LinkedList).

public Animal[] removeDuplicateAnimals(Animal[] animals) {
   Animal[] uniqueArray = new Animal[animals.length];
   int i = 0;
  
       for(int j=0; j<animals.length; j++){
           for(int k=0; k<animals.length; k++){
               if(j!=k && animals[k]==animals[j]){
               break;
               }
               if(j!=k && animals[k]!=animals[j]){
               uniqueArray[i++]=animals[j];
               break;
               }
       }
       }  

   return uniqueArray;
   }

Explanation / Answer

public Animal[] removeDuplicateAnimals(Animal[] animals)
{

// first count the unique Objects in the Array
int uniqueCount = 0;

for(int j = 0; j < animals.length; j++)
{

// checks for ArrayIndexOutOfBounds Exception
if(j != animals.length - 1)
{

// if 2 animals are not Same the increase the uniqueCount value


if(animals[j] != animals[j+1])
{
uniqueCount++;
}
}

}

// now create new Animal Array which is based on Only Unique Animals i.e length is UniqueCount



Animal[] uniqueArray = new Animal[ uniqueCount ];

int i = 0;

for(int j = 0; j < animals.length; j++)
{

// checks for ArrayIndexOutOfBounds Exception
if(j != animals.length - 1)
{

// if 2 Animals are not Same then Populate Animal in to new Array


if(animals[j] != animals[j+1])
{
uniqueArray[i] = animals[j];
}
}

}

// return the unique Array of Animals


return uniqueArray;

}