Generics / Integer to int

hello all, this is my first post. here's my code :

Iterator<Integer> i = list.iterator();

while( i.hasNext() ){

if( i.next() < intMethod() )

count++;

}

^Error: operator < cannot be applied toInteger,int

ok, my mistake, i tried this:

[...]

while( i.hasNext() ){

if( i.next().intValue() < intMethod() )

count++;

}

^Error: cannot find symbol

symbol: method intValue()

location: class java.lang.Object

why Integer earlier, and now Object.what'd i do wrong ?

thanks.

good day.

[856 byte] By [john_p12a] at [2007-11-27 1:29:54]
# 1

Providing you are talking about a List<Integer> how about:

for (Integer i: list) {

if (i < intMethod()) {

count++;

}

}

Message was edited by:

ChristopherAngel

ChristopherAngela at 2007-7-12 0:30:08 > top of Java-index,Java Essentials,New To Java...
# 2

I tried

ArrayList<Integer> myList = new ArrayList<Integer>();

myList.add(1);

Iterator<Integer> itr = myList.iterator();

while (itr.hasNext()){

if (itr.next().intValue() < 5){

System.err.println("less than 5");

}

}

I am not getting any compiler error !

Satish_Patila at 2007-7-12 0:30:08 > top of Java-index,Java Essentials,New To Java...
# 3
well its the same as my first problem,you can't compare Integer to int.i am not familiar with this style of coding (in your post), sorry !
john_p12a at 2007-7-12 0:30:08 > top of Java-index,Java Essentials,New To Java...
# 4
well yeah, i've also seen the use of :i.next().intValue();when i googled it, but it didn't work for me
john_p12a at 2007-7-12 0:30:08 > top of Java-index,Java Essentials,New To Java...
# 5
As for the reasons for failure I imagine that although you're using generics (a compile time validation) i.next() is not 100% guaranteed to be an integer at runtime so this doesn't auto-box.
ChristopherAngela at 2007-7-12 0:30:08 > top of Java-index,Java Essentials,New To Java...
# 6
then why does it work for Satish_Patil's post ?
john_p12a at 2007-7-12 0:30:08 > top of Java-index,Java Essentials,New To Java...
# 7

> Providing you are talking about a List<Integer> how about:

>

> for (Integer i: list) {

>if (i < intMethod()) {

>count++;

> }

> }

You can even simplify that one more step to:

for (int i: list) {

if (i < intMethod()) {

count++;

}

}

DrLaszloJamfa at 2007-7-12 0:30:08 > top of Java-index,Java Essentials,New To Java...
# 8
is i an iterator or int ?
john_p12a at 2007-7-12 0:30:08 > top of Java-index,Java Essentials,New To Java...
# 9

> is i an iterator or int ?

If you are referring to:

for (int i: list) {

Then variable i is of type int. There is an iterator driving that loop,

but the "enhanced for loop" uses a bit of syntactic sugar to keep

it implicit.

DrLaszloJamfa at 2007-7-12 0:30:08 > top of Java-index,Java Essentials,New To Java...
# 10
ok thanks
john_p12a at 2007-7-12 0:30:08 > top of Java-index,Java Essentials,New To Java...