comparing element in arraylist with an integer value in java - java

I have loaded the contents of the database in an ArrayList named countList. The contents loaded are of int type. I created countList using the command
ArrayList countList = new ArrayList();
Now, I need to check if each contents of the arraylist is greater than three. I wrote it like
for(int i=0; i< itemset.size(); i++){
if(countList.get(i) >= 3)
{
}
}
When I write it simply, it shows error of bad operand type for binary operator '>='. How to do the task?

The >= operator is only defined on number types such as int, double or Integer, Double. Now, countlist may well contain integers (I assume it does), but the way you have written your code, the compiler can't be sure. This is because an ArrayList can store any type of object, including but not necessarily Integer. There are a couple of ways you can remedy this:
a) You can cast the ArrayList item to an Integer, at which point the >= operator will work:
if ( (Integer) countList.get(i) >= 3)
b) You can use generics to tell the compiler that your ArrayList will ONLY store Integers:
ArrayList<Integer> countList = new ArrayList<Integer>();

for(i=0; i< itemset.size(); i++){
if (itemset.get(i) > 3) {
// Do whatever you want here
}
}

Related

Iterate over a list of autobox type in Java

If I populate a list like this
List<Integer> l = new ArrayList<>();
for(int i = 0; i < 1000000; ++i) {
l.add(i);
}
What is the best way to iterate over this list (in term of code cleanliness and efficiency) :
With the autobox type
for(Integer i : l) {
// do stuff...
}
or with the primitive type
for(int i : l) {
// do stuff...
}
Actually, the first loop - for(Integer i : l) - has no auto-boxing, since l is a List<Integer>. The auto-boxing takes place when you add the elements to that List.
On the other hand, the second loop - for(int i : l) - has auto-unboxing of the Integer elements to ints.
As to which one is better, it depends on what you are going to do with the elements.
If, for example, you are going to add them to another List (or check if they are keys of some Map), there's no need to unbox them, so you can use the first loop.
If, one the other hand, you're going to do numeric operations on them (such as computing their sum), you'll have to unbox them anyway, so you might as well go with the second loop.
i tried the both option for calculate the sum of the list and ths is the result

Check if array does NOT contain a certain value

I know that if I want to check if an array does contain a certain value I should use Arrays.asList(arrayName).contains(valueName).
But how do I check if that value is not present? At first I just thought of putting ! in front like:
!Arrays.asList(arrayName).contains(valueName)
but that doesn't seem to work.
I even tried writing the if statement like this:
if (Arrays.asList(arrayName).contains(valueName)==false)
but that doesn't seem to work either.
Here is the code:
public int[] duplikati(int[] tabela){
int len = tabela.length;
int c = 0;
int[] count = new int[len];
for (int i=0;i<len;i++){
if (Arrays.asList(count).contains(tabela[i])==false){
c++;
}
}
int[] result = new int[c];
int d = 0;
for (int j=0;j<len;j++){
if (Arrays.asList(result).contains(tabela[j])==false){
System.out.print(tabela[j]+" ");
result[d] = tabela[j];
d++;
}
}
return result;
}
In, this specific case when you pass an array of primitive types into Arrays.asList you'll get back a List with a single element which is the provided array.
So, when you do:
Arrays.asList(arrayName).contains(valueName)
The call Arrays.asList(arrayName) will return a List<int[]> and then when you call contains the valueName will get boxed to an Integer and then get's compared with the element(s) in the list. because an int[] is never equal to an integer value, the contains call will always return false.
Solution 1 - change the type of your arrays from int[] to Integer[], then everything should work as you expect.
Solution 2 - Assuming you do not want to change the type of the arrays for some reason, then you can do:
final int index = i;
if(Arrays.stream(count).noneMatch(e -> e == tabela[index])){...}
inside the for loops.
You can think of the noneMatch method as !Arrays.asList(someArray).contains(someValue) if it helps.
Similarly, you can check if the array contains an element with:
final int index = i;
if(Arrays.stream(count).anyMatch(e -> e == tabela[index])){...}
You can think of the anyMatch method as Arrays.asList(someArray).contains(someValue) if it helps.
You can use Java 8 stream api as follows
Integer arr[]=new Integer[]{1,2,30,61};
System.out.println(Arrays.asList(arr).stream().noneMatch(element>element==10));
You can go through the below link for explaination of
noneMatch()

How to get the sum of an LinkedList (Sum up items in a LinkedList)

What I'm trying to do is get the sum of all integer items retrieved from the database then added into a LinkedList, like so:
ManageFeeNotePOJO selectedRecord = (ManageFeeNotePOJO) manageFeeNoteListTableView().getItems().get(selectdIndex);
List toFeeBillListTot = new LinkedList();
toFeeBillListTot.add(selectedRecord.getFeeNoteValue());
int sum = 0;
for (Object sumItem : toFeeBillListTot) {
sum += sumItem;
}
System.out.println(sum);
With this I get the error:
bad operand types for binary operator '+'
first type: int
second type: Object
The other approach is:
ManageFeeNotePOJO selectedRecord = (ManageFeeNotePOJO) manageFeeNoteListTableView().getItems().get(selectdIndex);
List toFeeBillListTot = new LinkedList();
toFeeBillListTot.add(selectedRecord.getFeeNoteValue());
int sum = 0;
for (int i = 0; i < toFeeBillListTot.size(); i++) {
sum += (int) toFeeBillListTot.get(i);
}
System.out.println(sum);
I get java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer error with this
Please, I would be more than greatful for any working approach around this. Thank you in advance.
bad operand types for binary operator '+'
first type: int
second type: Object
This is saying: "You can't use the + operator with one these two types" - and I bet you can guess which one - Object - which, if you think about it, makes sense:
Remember that every class of every type you'll ever work with in Java extends Object. So, when you're working with something that has been cast to Object, Java knows almost nothing about what that something is. In particular, it would have no freaking clue what to do with a + applied to one.
For instance, imagine that you had a Person class and did
Person a = new Person();
Person b = new Person();
a + b; //WTF??
Would that make sense? Of course not.
Now, you might say "but I didn't add Objects to my list, I added Integers/Doubles/some other type that the + operator should work with" - and I'm sure you would be right, but the problem is that you added them to a List of Objects, which you created as such right here:
List sum toFeeBillListTot = new LinkedList();
When you do this, you're creating an "untyped list". This means you can add objects of any type you like to it - which might sound nice, but as a natural consequence, you can only retrieve Objects from it, which is what you're doing now.
By "use a generic collection", #Jeroen is suggesting you do this instead:
List<Integer> toFeeBillListTot = new LinkedList<>();
Rather than creating a list of Objects, the <Integer> means you're creating a list of integers, which means you can only add Integers to it, and also that every element you pull out of it will be an Integer, so you can do:
int sum = 0;
for (Integer sumItem : toFeeBillListTot) {
sum += sumItem;
}
First, I feel a bit weird about the use of raw types with your List declaration. By that, I mean you do not provide the type argument to it.
If you've got an expectation that you're getting back a list of Strings, then you should declare it as such:
List<String> toFeeBillListTot = new LinkedList<>();
Next, you can't simply add up Strings, as that has no meaning. You have to convert them all to some numerical type, probably Double:
double sum = 0;
for(String bill : toFeeBillListTot) {
sum += Double.parseDouble(bill);
}
Not that the above conversion will only work if there aren't any other unusual characters in your conversion (that is, no thousands separators).

Analyze / Filter all variables without declaring each one?

Say you have 70 separate int variables, and you wanted to analyze all of them and set any one which equals zero to 1, or another number.
Instead of writing 70 if else statements for each variable, can you write only one?
Is there a way to do something like this:
if("anyInt"==0){
"thatInt" = 1;}
?
(should mention I have no idea what a "collection" is)
use an int[] Then iterate through them using a for loop
int[] nums = new int[70];
//put all your numbers in the array, i.e. nums[0] = 5;
for(int i = 0; i < nums.length; i++){
if(nums[i] == 0){
//Do whatever to the number
}
}
If you need names for all of these values, put them in a Map (which is a collection):
Map<String, Integer> myMap = new HashMap<String, Integer>();
myMap.put("varname1",1);
myMap.put("varname2",0);
myMap.put("varname3",0);
myMap.put("varname4",2);
for (Map.Entry e : myMap.entrySet())
if (e.getValue()==0) e.setValue(null);
You will need to import the collections (i.e. import java.util.*;).
The integer values are auto-boxed and unboxed between int and Integer.
Without knowing anything else about your code, I would say that you should have the variables in an int array.
Then you would be able to loop through the array and only have one if statement.

Setting a generic ArrayList to zeros

I have an ArrayList. I would like to set each element of it to 0. Right now I have:
ArrayList <T extends Number> arr = new ArrayList();
for(int i = 0; i < some_other_array.size(); i++)
{
arr.add(0)
}
The compiler complains that
error: no suitable method found for set(int,int)
arr.add(0);
^
method ArrayList.set(int,T) is not applicable
(actual argument int cannot be converted to T by method invocation conversion)
where T is a type-variable:
T extends Number
It cannot be done. The method signature for is
public T ArrayList<T>.set(int index, T element)
Even though the constraint on T is that it extends Number, it does not mean that it can be constructed from a number.
Consider, for example,
class FortyTwo extends Number {
public byteValue() { return 42; }
public intValue() { return 42; }
// etc
}
What would you expect the initialization routine to do to an ArrayList<FortyTwo> ?
Just change your list declaration to
ArrayList<Number> arr = new ArrayList<Number>();
arr will be capable of holding anything extending Number (which is what you want, I assume).
Now, when you do
arr.set(i, 0)
that 0 will be autoboxed to an Integer. (See for yourself, add 0 and print arr.get(0) instanceof Integer.)
If you wanted to add doubles or longs for instance, you could use the literals 0d and 0L, respectively.
This should work for your case: arr.set(i, Integer.valueof(0));
Or you can reuse this handy standard API: Collections.fill(arr, Integer.valueof(0));
Why you want to set the value to 0, it will be automaticaly zero as ArrayList object will be instantiated. So the code will be useless as the size will be zero at the time so loop will not be executed.
Well, I think you're a little confused about how ArrayList actually works. When you create an ArrayList, it's always empty. Even if you specify a size:
ArrayList<Integer> arr = new ArrayList<Integer>(20);
That 20 just means "initial capacity", not "starting number of elements". As a result, set will never work because there are simply no elements. Even if you fix your compiler issue like this:
arr.set(i, Integer.valueOf(0));
Or like this:
ArrayList<Number> arr = new ArrayList<Number>();
It's not even going to do anything because arr.size() is zero, so the for loop won't even run.
The key here is that ArrayList is not an actual array. It wraps an array, and will expand its inner array when it has too many elements. In other words, I can't do this:
ArrayList<Integer> arr = new ArrayList<Integer>(20);
arr.get(0); // Throws an out of bounds exception
Now, that being said, if you want to start with 20 zeroes in your ArrayList, you can use the add method in your loop and i < 20 instead:
for(int i = 0; i < 20; i++) {
arr.add(Integer.valueOf(0));
}
This will add 20 zeroes to arr. Your code, even after fixing the error, will not.
Try changing the declaration of your ArrayList to
ArrayList<Integer> arr = new ArrayList<Integer>();
The Integer class supports auto-boxing, while the Number class does not. Also, the add() method may be more applicable.
You can try this (to the best of my knowledge, you cannot add primitive types to ArrayList):
ArrayList<Integer> arr = new ArrayList<Integer>();
for(int i = 0; i < someNumber; i++)
{
arr.add(0);
}
Remember that when size is 0 because it does not have any default values and the capacity is what you should be looking at (You can set the capacity in the constructor.)

Categories