Create a list of numbers.
Use the keyboard to add 10 numbers to the list.
Display the length of the longest sequence of repeating numbers in the list.
This are the required conditions.
This is my code. It works, but I don't understand something. In the while loop, first I tried to compare directly the ArrayList elements, since they were of int type. The algorithm worked with small numbers, like(1,1,1,4,4,4,4,4,4). But it failed and I got a hint that I should try with numbers larger than 127, and of course it didn't work. Running in debug mode I noticed that something was wrong in the while loop, at comparing the ArrayList elements. IntelliJ gave me the solution, and it works. But I don't quite understand why my initial solution didn't work, since I was comparing int's. I wonder, if the number is larger that 127 it is considered an Object? Are there any articles about this?
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
String s = reader.readLine();
int number = Integer.parseInt(s);
list.add(number);
}
int result = 0;
int temp = 0;
for (int i = 0; i < list.size() - 1;i++) {
int j=i;
while(Objects.equals(list.get(j), list.get(j + 1))){
temp += 1;
if(j==8){
break;
}
j++;
}
if (temp+1> result) {
result = temp + 1;
temp = 0;
}
else{
temp=0;
}
}
System.out.println(result);
}
}
catalin1989
Level 37
Why I can't use "==" operator with ArrayList with list elements larger that 127 and have to use Object.equals(list.get(j), list.get(j+1))?
Under discussion
Comments (2)
- Popular
- New
- Old
You must be signed in to leave a comment
Thomas
22 September 2023, 10:25
The surprise is actually not that numbers from 128 can only be compared with equals, but that numbers between -128 and 127 can be compared with ==. After all, Integer is a class and not a primitive. And with objects the == operator compares references not values.
That possibility is achieved by the fact that up to 127 all objects in the integer class are already created in advance. If the programmer now tries to create an integer himself (with valueOf or auto boxing), then valueOf returns a reference to the object already created in advance. So always the same reference for all created integer objects with the value e.g. 17. From 128 on there is no more caching and for each call of the valueOf method a new object is created, which then also has a different reference.
The (deprecated) constructor does not consider this caching (interning) by the way.
0
catalin1989
22 September 2023, 17:31
Thanks for the reply. So, I think that I made an error in my thinking. When I create an ArrayList with the argument<Integer> I am passing to the array list, an object that has a value. If I want to compare these values I have to use equals. In my code, when I used == it compared the references of the object, and since they were not equal it returned false.
0