Reputation: 95
Is there a way that I can compare an array and an arraylist like
if (array[0]==arraylist[0])
I am working on this problem:
String[] s= {"a","a","b","b","b","c"};
ArrayList<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
// create a new arraylist that stores the frequency of each character.
// For example, "a" appears twice in s, so newArrayList[0]=2; "b" appears
// three times, so newArrayList[1]=3, and so on.
My idea is using a loop to scan through the string array and every time when a letter in it equals the letter in list, int count++. But I dont know how to compare things in an array and things in an arraylist.
Upvotes: 1
Views: 11761
Reputation: 1
import java.util.ArrayList;
public class ArrayAndArrayListElementsComparison {
public static int compareArrayAndArrayListElements(String[] array, ArrayList<String> arraylist) {
int count = 0;
for (String s : array) {
if (arraylist.contains(s)) {
count++;
}
}
return count;
}
public static void main(String[] args) {
String[] array = {"a", "a", "b", "b", "b", "c"};
ArrayList<String> arraylist = new ArrayList<String>();
System.out.println("");
arraylist.add("a");
arraylist.add("b");
arraylist.add("c");
if (!arraylist.isEmpty() && array.length > 0) {
if (compareArrayAndArrayListElements(array, arraylist) == array.length) {
System.out.println("ArrayList contains all the elements in Array");
} else if (compareArrayAndArrayListElements(array, arraylist) > 0) {
System.out.println("ArrayList contains only few elements in Array");
} else {
System.out.println("ArrayList contains none of the elements in Array");
}
} else {
System.out.println("Either ArrayList or Array is Empty.");
}
}
}
Upvotes: 0
Reputation: 62
You try
if (array[0].equals(arraylist[0]))
As in java comparisons string should use equals(). It's not like javascript.
Upvotes: -1
Reputation: 5949
Yes, you can iterate through the array and arraylist and compare elements. ArrayList elements are accessed with .get(index)
. And if you are comparing Objects (non-primitives), you need to use the .equals()
method, not ==
.
if(array[i].equals(arrayList.get(i) ) )
Upvotes: 1