I have such simple code:
import java.util.ArrayList;
import java.util.List;
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Integer[] tab = {2324,1,2,2324,3,45,1,5,0,9,13,2324,1,3,9,8,4,2,1};
Integer max = 2324;
List<Integer> indexes = new ArrayList<Integer>();
for (int e = 0; e < tab.length; e++) {
if (tab[e] == max) {
indexes.add(new Integer(e));
System.out.println("Found max");
}
}
}
}
The main problem here is I want to find every index in my tab where the max value is. For now on, it doesnt work - it doesnt display Found max message even once, although it should do it 3 times. Wheres the problem?
Ok, this finally worked, thanks all of you people:
public static void main(String[] args) {
Integer[] tab = {2324,1,2,2324,3,45,1,5,0,9,13,2324,1,3,9,8,4,2,1};
Integer max = 2324;
List<Integer> indexes = new ArrayList<Integer>();
for (int e = 0; e < tab.length; e++) {
if (tab[e].intValue() == max.intValue()) {
indexes.add(Integer.valueOf(e));
System.out.println("Found max");
}
}
}
Change
Integer[] tab = {2324,1,2,2324,3,45,1,5,0,9,13,2324,1,3,9,8,4,2,1};
to
int[] tab = {2324,1,2,2324,3,45,1,5,0,9,13,2324,1,3,9,8,4,2,1};
Integer objects are only precached for the values from -128 to 127.
If you want to leave it Integer you can change
if (tab[e] == max) {
to
if (tab[e].equals(max)) {
because it will then check for object equality, and not reference equality.
That's because you are comparing with == and not equals.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With