How to compare arraylist value and array value in java - java

int sizeOfTheShortestList = webresult.size();
for (int i=0; i<sizeOfTheShortestList; i++) {
if (webresult1.get(i).equals(dbresult[i]) )
{
System.out.println("Equals..: " + webresult1.get(i));
}
}
from above code i find errors please give solution to compare arraylist values and array values

Take arraylist as 'al'.
Take array as 'a'.
now u need to compare 'al' and 'a'.
iterator it = new iterator(al);
int length = a.size();
int count=0;
for(int i=0;i<length; i++)
{
if(it.next()==a[i]);
{
count++;
}
}
if(count == length)
{
System.out.println("Both are equal");
}
else
{
System.out.println("Both are not equal");
}

You could use something like ArrayList#retailAll
Retains only the elements in this list that are contained in the
specified collection. In other words, removes from this list all of
its elements that are not contained in the specified collection.
webresult.retainAll(Arrays.asList(dbresult);
// Now webresult will only contain the values that were in webresult and are in dbresult

Try some thing like this
int sizeOfTheShortestList = Math.min(webresult.size(), webresult1.length);
for (int i=0; i<sizeOfTheShortestList; i++) {
if (webresult.get(i).equals(webresult1[i]) {
System.out.println("Equals..: " + webresult.get(i));
}
}
I hope I understood your question in right way..otherwise please comment

First you need to compare the lengths of both webresult and dbresult, because if they are of different lengths you will get IndexOutOfBounds exception.
Is webresult.get(i) is of the same type as of dbresult[i]?
Implementation of equals, missing from question, should add that too, if not using default.

It depends on what kind of errors you get.
Another solution would be to use the toArray() method on your arraylist and compare 2 arrays. But your code should work if the data structures have the same length, because you are comparing the elements from the array and arraylist, not the collections themselves.

Assuming that your arraylist is shorter than the array (otherwise you'd get an IndexOutOfBounds exception), you should make sure that the types of webresult.get(i) and dbresult[i] are the same. Also, ".equals()" only works for comparing objects (such as Strings), and not for primitives. So if webresult.get(i) and dbresult[i] are ints or chars, ".equals" will not work. You should use "==" instead.

You can use the ArrayList#toArray() to convert your list to an array.
Then you can use Arrays#equals() to compare the two arrays.
The objects that you are comparing will have to override Object#eqauls()

Related

HashMap dont stay stable in android

Hi I am trying to save a object in HashMap if it is not exist than if it is exsit I want to control its value with new data. If data change than I want to do sth. else. But whenever I tried to compare new data and hash value I saw they are same on every time . How can I handle with this issue. There is code:
BluetoothLeDevice deviceLe;
private Map<String, byte[]> mMacMap;
byte [] integer0 =new byte[4];
byte[] tempInteger0=new byte[4];
public void addSensor(String macId, BluetoothLeDevice deviceLe) {
byte [] addSensorrecord=deviceLe.getScanRecord();
int j=0;
for(int i=15;i<19;i++)
{
integer0 [j]=addSensorrecord[i];
j++;
}
if (mMacMap.containsKey(macId)) {
tempInteger0 = mMacMap.get(macId);
if(!integer0 .equals(tempInteger0))
{
mMacMap.remove(macId);
mMacMap.put(macId, integer0 );
new SendBLEData().execute(deviceLe);
}
} else {
final byte [] LocalInteger0=new byte[4];
int t=0;
for(int i=15;i<19;i++)
{
LocalInteger0[t]=addSensorrecord[i];
t++;
}
mMacMap.put(macId, LocalInteger0);
new SendBLEData().execute(deviceLe);
}
}
I am guessing, that your problem is here:
!Integer0.equals(tempInteger0))
I think you want to compare two arrays; and you are surprised to find them to be different ... all the time.
Your problem is: equals() on arrays doesn't do a comparison of the array content. In other words: this call to equals() only gives "true" if the arrays you are comparing ... are one and the same, like in:
int a[] = { 1 };
int b[] = a;
int c[] = { 1 };
Here:
a.equals(b) --> true
but
a.equals(c) --> false
When comparing array content matters, then you should use ArrayList instead. Because two ArrayList objects are equal when they contain exactly the same equal elements.
And you see: you are using that equals on arrays to make a decision in your code. So, you either change to ArrayLists; or use Arrays.equals() as user hamsty suggested.
Just a few additions to the already posted answers.
The remove below is not necessary, a simple put will replace the old value
mMacMap.remove(macId);
mMacMap.put(macId, integer0 );
From the javadoc
If the map previously contained a mapping for the key, the old value
is replaced by the specified value. (A map m is said to contain a
mapping for a key k if and only if m.containsKey(k) would return
true.)
Have you considered making bytes 15-19 into a string and adding them onto the maps key? This would eliminate the array compare and make the lookups much faster.
!Integer0.equals(tempInteger0))
is your problem.
Use this to compare the content of arrays:
Arrays.equals(Integer0, tempInteger0)
The problem is the following sequence of events:
macId not in mMacMap, insert new byte[4]; into the map
macId in mMacMap, the array created in the previous step never matches integer0 due to the Array comparison problem mentioned by the other answer, replace macId in the map with a reference to integer0
macId in mMacMap, since the array is a reference to integer0, it will always compare positively and the contents will no longer be updated.
Repeat 3.
Basically caused by these two issues:
Array#equals does not behave intuitively, use the static method Arrays.equals
Java is heavily reference-based, so if you insert something into a map it will not be copied, but simply a new reference is created; this may bite you if you change a shared object afterwards (like the array).

Can I iterate over two arrays at once in Java?

For one array I can iterate like this:
for(String str:myStringArray){
}
How can I iterate over two arrays at once?
Because I am sure these two's length are equal.I want it like the following:
for(String attr,attrValue:attrs,attrsValue) {
}
But it's wrong.
Maybe a map is a good option in this condition, but how about 3 equal length arrays? I just hate to create index 'int i' which used in the following format:
for(int i=0;i<length;i++){
}
You can't do what you want with the foreach syntax, but you can use explicit indexing to achieve the same effect. It only makes sense if the arrays are the same length (or you use some other rule, such as iterating only to the end of the shorter array):
Here's the variant that checks the arrays are the same length:
assert(attrs.length == attrsValue.length);
for (int i=0; i<attrs.length; i++) {
String attr = attrs[i];
String attrValue = attrsValue[i];
...
}
You can do it old fashion way.
Assuming your arrays have same sizes:
for(int i = 0; i < array1.length; i++) {
int el1 = array1[i];
int el2 = array2[i];
}
In Scala there is an embedded zip function for Collections, so you could do something like
array1 zip array2
but it's not yet ported to Java8 Collections.
Foreach loop has many advantages but there are some restriction are also there.
1: You can iterate only one class(which implements Iterable i/f) at one time.
2: You don't have indexing control. (use explicit counter for that.)
For your problem use legacy for loop.

Common elements of muiltiple arrays but not using Lists

Is there a way i could return in an array the common elements of 2 or more arrays? I know having some of the methods under lists could do it but is there a way to do it by only using arrays? I made my own get and length btw since i am creating a an array called OrderedIntList.
Example would be:
1,3,5
1,6,7,9,3
1,3,10,11
Result: 1,3
I tried this and it outputs the common elements between two arrays and not all.
I know there's something wrong but i do not how to make it work like it suppose to work :(
//returns the common elements of inputted arrays
public static OrderedIntList common(OrderedIntList ... lists){
int[] list = new int[10];
for(int x = 1; x <= lists.length -1; x++){
for(int q = 0; q < lists[0].length()-1; q++) {
for(int z = 0; z < lists[x].length(); z++) {
if (lists[0].get(q)==lists[x].get(z)){
list[q] = lists[0].get(q);
}
}
}
}
OrderedIntList newlist = new OrderedIntList(list);
return newlist;
}
This can be an easy algorithm to solve it...
1) Instantiate an instance variable of type array called
"commonElements" pointing to the elements of the first Array. At the
beginning these are your common elements.
2) Create a method call getCommonElements(int[] commonElements,
int[] newList). This method manipulates the commonElements array to leave
it with only the common elements between the two. (p.s Use a temporary
array to achieve this if you find it easier)
3) Iterate over all the arrays present in "lists" starting from the
second array.
4) call the method at point 2 for each array .
All the difficult part for you it's to implement a method that given 2 arrays finds the common elements!
You can use
org.apache.commons.collections.CollectionUtils.intersection(java.util.Collection a, java.util.Collection b)
to get the intersection of two lists (elements presents in both lists)
And to pass your array as a Collection: java.util.Arrays.asList(Object[] a);
But working on arrays is tedious, at best. You should consider why you don't want to use a Collection...
As a partial answer, you're probably doing too much work by fully reimplementing an OrderedIntList the way you're doing, since ArrayList and friends already come with sorting baked in via the Collections class.
import java.util.Collections;
public class OrderedIntList extends ArrayList<Integer> {
#override // to effect sorted inserts
public void add(Integer i) {
this.add(i);
Collections.sort(this);
// done.
}
}
Wanting to do this for pure arrays is a nice exercise, but then you'll be better of implementing sorting properly with a quick sort (you can't websearch for a java implementation of that without getting a million results) or an insert sort (equally websearchable), and follow the same recipe.
any time you push a number into the array:
guess where the number goes (although that's optional),
insert the number,
resort your array if you know your guess wasn't perfect.

Shorter way to compare two lists and remove values that are in both?

I'm trying to compare two ArrayLists and remove values from a list if they appear on a second one. Both lists contain the same class: "EditableListItem.
ArrayList<EditableListItem> items = new ArrayList<EditableListItem>();
ArrayList<EditableListItem> addedItems = new ArrayList<EditableListItem>();
I have written this code, which does the job however I don't feel it's a very good solution.
int remove_n = -1;
for(int k=0;k<addedItems.size();k++)
{
for(int i=0;i<items.size();i++)
{
if(items.get(i).getKey().equals(addedItems.get(k).getKey()))
{
remove_n = i;
}
}
if(remove_n > -1)
{
items.remove(remove_n);
remove_n = -1;
}
}
Is there a way to do this with less lines? Or maybe using some method from ArrayList?
Thanks
You can use ArrayList#removeAll(Collection c), e.g. items.removeAll(addedItems).
If you want it to run faster, make a HashSet from one collection, then call its removeAll() method.
To remove all items from a collection that are in another collection, use removeAll.
items.removeAll(addedItems);
You could note down all the array indices (in both arrays) where array elements are the same, and one you iterate thrrough both lists, remove the common elements using
items.remove(index);
method.
Don't remove without iterating completely through both the arraylists, because when you remove one element, the array indices for all subsequent elements change.
Else, if you would like to do it in one loop itself, as and when you delete the element, decrement your loop variable by one, so that index associativity is maintained for both arraylists.

Hashset objects

I'm writing a piece of code which takes a great deal of objects and adds them to another array. The catch is, I don't want any duplicates. Is there a way I could implement a Hashset to solve this problem?
public static Statistic[] combineStatistics(Statistic[] rptData, Statistic[] dbsData) {
HashSet<Statistic> set = new HashSet<Statistic>();
for (int i=0; i<rptData.length; i++) {
set.add(rptData[i]);
}
/*If there's no data in the database, we don't have anything to add to the new array*/
if (dbsData!=null) {
for (int j=0; j<dbsData.length;j++) {
set.add(dbsData[j]);
}
}
Statistic[] total=set.toArray(new Statistic[0]);
for (int workDummy=0; workDummy<total.length; workDummy++) {
System.out.println(total[workDummy].serialName);
}
return total;
}//end combineStatistics()
Properly implement equals(Object obj) and hashCode() on YourObject if you expect value equality instead of reference equality.
Set<YourObject> set = new HashSet<YourObject>(yourCollection);
or
Set<YourObject> set = new HashSet<YourObject>();
set.add(...);
then
YourObject[] array = set.toArray(new YourObject[0])
I think you should pay attention to:
1 - what to do if there is a duplicate in the original Collection? Use the first added to the array? Use the other(s)?
2 - You definitely need to implement equals and hashcode so that you can tell what are duplicate objects
3 - Are you going to create a fixed size array and then won't add anymore objects? Or are you going to keep adding stuff?
You can use any kind of Set actually, but if you use LinkedHashSet, then you will have a defined iteration order (which looks like an array). HashSet wont't garantee any order and TreeSet will try to order data ascending.
Depends on what you are referring to as a duplicate. If you mean an identical object, then you could use a List and simply see if the List contains the object prior to adding it to the list.
Object obj = new Object();
List<Object> list = new ArrayList<Object>();
if (!list.contains(obj)) {
list.add(obj);
}

Categories