In: Computer Science
Write in Java:
Write a method called:
public static String[] noIdenticalCombine(String[] array1, String[] array2)
{
// instructions: returns an array that contains all the Strings in array1 and array2 but without repetition.
order does not matter, but it will return array1's elements and then array2's element that are not in array1.
Assume there are no duplicates are in array1 and array2.
Could use count which is how many str there are in array2, where !contains(array1, str). May an array of length array1.length + count. Copy elements from array1 into new array then copy elements in array2 where !contains(array1, str). Return the new array.
Both array1 and array2 are not null or empty. OR strings in array1 or array2 is null.
}
Program Code Screenshot :
Sample Output :
Program Code to Copy
import java.util.Arrays; class Main{ //Combine two strings and elimiate duplicates public static String[] noIdenticalCombine(String[] array1, String[] array2) { //Find the common elements in array2 which are in array1 int count = 0; for(int i=0;i<array2.length;i++){ boolean found = false; for(int j=0;j<array1.length;j++){ if(array2[i].equals(array1[j])){ found = true; break; } } if(!found){ count++; } } //Create a new array String[] ans = new String[array1.length+count]; //Copy first array to the answer for(int i=0;i<array1.length;i++){ ans[i] = array1[i]; } int ind = array1.length; for(int i=0;i<array2.length;i++){ boolean found = false; for(int j=0;j<array1.length;j++){ if(array2[i].equals(array1[j])){ found = true; break; } } //If element is not present in array1, add it to ans if(!found){ ans[ind++] = array2[i]; } } return ans; } public static void main(String[] args) { String a[] = {"a","b","c","d"}; String b[] = {"b","d","e","f"}; System.out.println(Arrays.toString(noIdenticalCombine(a,b))); } }