package Interview ;
import java.util.Arrays;
public class CompareArray {
public static void main(String[] args)
{
// String[] elements = new String[]{"element1", "element2", "element3"};
//OR//
String[] stringElements = {"element1", "element2", "element3", "element4"};
int[] intElements = {11,12,13,14,15};
//all elements in the array
System.out.println("All String elements = "+ Arrays.asList(stringElements));
//System.out.println("All int elements = "+ Arrays.asList(intElements));
System.out.println("index of element3 = "+ Arrays.asList(stringElements).indexOf("element3"));
System.out.println("index of 14 = "+ Arrays.asList(intElements).indexOf(14));
System.out.println("String value at index 2 = "+ Arrays.asList(stringElements[2]));
System.out.println("int value at index 2 = "+ Arrays.asList(intElements[2]));
String[] chrElements = {"element1", "element2", "element3", "element4"};
// compare arrays, right approach
if (Arrays.equals(stringElements, chrElements)) {
System.out.println("Third Test, Right Approach, Same Arrays");
return ; // takes you out of the method if satisfied
} else {
System.out.println("Third Test, NOT Same Arrays");
}
//compare arrays
if (stringElements==chrElements){
System.out.println("First Test, Same Arrays");
return ;
} else {
System.out.println("First Test, NOT Same Arrays");
}
//compare arrays
if (stringElements.equals(chrElements)){
System.out.println("Second Test, Same Arrays");
return ; // takes you out of the method if satisfied
} else {
System.out.println("Second Test, NOT Same Arrays");
}
//check if an element is present in array
System.out.println("array length = "+stringElements.length);
for(int a=0; a<stringElements.length; a++){
if("element3" == stringElements[a] ){
System.out.println("Element Present");
return ;//or break; // takes you out of the method if satisfied
} else {
System.out.println("Element NOT Present");
}
}
}
}
Output1:
All String elements = [element1, element2, element3, element4]
index of element3 = 2
index of 14 = -1
String value at index 2 = [element3]
int value at index 2 = [13]
Third Test, Right Approach, Same Arrays
When you comment out or remove the “return” in first compare code
Output2:
All String elements = [element1, element2, element3, element4]
index of element3 = 2
index of 14 = -1
String value at index 2 = [element3]
int value at index 2 = [13]
Third Test, Right Approach, Same Arrays
First Test, NOT Same Arrays
Second Test, NOT Same Arrays
array length = 4
Element NOT Present
Element NOT Present
Element Present
No comments:
Post a Comment