Question with Arrays.asList ()
I have a very simple program and I just need to check an array for the value in it. I have a class called bulkBean. it's him.
public class bulkBean {
private int installmentNo;
private double amount;
public int getInstallmentNo() {
return installmentNo;
}
public void setInstallmentNo(int installmentNo) {
this.installmentNo = installmentNo;
}
public double getAmount() {
return amount;
}
public void setAmount(double amount) {
this.amount = amount;
}
}
Now I have an array of this bulkBean in my program, this is my program.
import java.util.Arrays;
public class test {
public static boolean scan_bulkList(bulkBean[] bulkList, int i) {
int[] arr = new int[bulkList.length];
for(int x=0;x<bulkList.length;x++){
arr[x] = bulkList[x].getInstallmentNo();
}
for(int j = 0; j< arr.length ;j++){
System.out.println("INFO: array "+j+" = "+arr[j]);
}
if (Arrays.asList(arr).contains(i) == true) {
return true;
} else {
return false;
}
}
public static void main(String[] arg){
bulkBean bb1 = new bulkBean();
bb1.setInstallmentNo(1);
bb1.setAmount(5500);
bulkBean bb2 = new bulkBean();
bb2.setInstallmentNo(2);
bb2.setAmount(4520);
bulkBean[] bulkArray = new bulkBean[2];
bulkArray[0] = bb1;
bulkArray[1] = bb2;
boolean a = scan_bulkList(bulkArray,1);
System.out.println("val = "+a);
}
}
I am creating 2 instances of the bean array and I am setting values ββfor them. Then I added these two instances to the array. Then I pass this array to the method to check the value (also given as a parameter, in this case it is 1.). If the array contains this value, it must return true, otherwise false. whatever value i enter returns false. Why am I getting this problem?
As TheListMind said Arrays.asList()
, taken on int[]
, gives you a list containing an array.
Personally, I would create a List directly instead of creating an array, or even better (without having to initialize the array), checking when iterating over the array of the array:
for(int x=0;x<bulkList.length;x++){
if (bulkList[x].getInstallmentNo() == i){
return true;
}
}
return false;
Arrays.asList()
returns a list containing one element - an array. So you are actually comparing an array to an array. You need to compare against every value in the array.
The mistake you made here, you created an int array, which must be an Integer array, because that Arrays.asList().contains(Object o);
does the input parameter as well Integer(Integer i)
. int
is not an object Integer
. Hope it works.
int[] arr = new int[bulkList.length];
change to:
Integer[] arr = new Integer[bulkList.length];
Modify the method as shown below to avoid complications:
public static boolean scan_bulkList(bulkBean[] bulkList, int i) {
int[] arr = new int[bulkList.length];
for(int x=0;x<bulkList.length;x++){
arr[x] = bulkList[x].getInstallmentNo();
if (bulkList[x].getInstallmentNo()==i) {
return true;
}
}
return false;
}