109k views
4 votes
Write a method named isUnique that takes an array of integers as a parameter and that returns a boolean value indicating whether or not the values in the array are unique (true for yes, false for no). The values in the list are considered unique if there is no pair of values that are equal. For example, if a variable called list stores the following values:

int[] list = {3, 8, 12, 2, 9, 17, 43, -8, 46, 203, 14, 97, 10, 4};

Then the call of isUnique(list) should return true because there are no duplicated values in this list. If instead the list stored these values:

int[] list = {4, 7, 2, 3, 9, 12, -47, -19, 308, 3, 74};

Then the call should return false because the value 3 appears twice in this list. Notice that given this definition, a list of 0 or 1 elements would be considered unique.

User Inaps
by
5.1k points

1 Answer

2 votes

Answer:

// isUnique method is defined

// it return a boolean

// it is static so that it can be called from main method

// it takes an array as argument

public static boolean isUnique(int[] array){

// the outer for-loop

for(int i = 0; i < array.length; i++){

// the inner for-loop

for(int k = 0; k < array.length; k++){

// if the index of i and k is same

// it continues to avoid comparing same element with itself

if (i == k) continue;

// if two values are found to be same

// it returns false

// to show that array is not unique

if(array[i] == array[k]){

return false;

}

}

}

// the default return statement for the method

return true;

}

Step-by-step explanation:

The isUnique method also returns true if the list has 0 or 1 elements. The isUnique method uses nested for loop to check for duplicate elements. The method is also well commented.

User Hui
by
4.8k points