Find max element in Java ArrayList - java

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.

You are using the == operator in something that it is not the primitive int, but an instance of class Integer. Basically, you are comparing the references of both objects, which are different. Try using :
if(tab[e].equals(max))

The basic problem you have is that you are using Integer, not int One difference being that as Integer is an object == compares the references to two different objects. (Not he contents of those objects)
I suggest you use primitives like int instead of objects where you can.

You can only compare primitive values with ==. Since Integer is an object, change tab[e] == max to tab[e].equals(max).
Look for equals vs ==
Also read: Java: int vs integer

The JVM is caching Integer values.
== only works for numbers between -128 and 127
See explanation here: http://www.owasp.org/index.php/Java_gotchas#Immutable_Objects_.2F_Wrapper_Class_Caching

try this:
if (tab[e].intValue() == max.intValue()) {
or
if (tab[e].intValue() == max) {
If you are using Integer object rather than primitive int, then with comparison operator like == , atleast one operand should be primitive one (other will be converted implicitly).
Or you should use equals method for equality

Use one of the three : 1. tab[e].intValue() == max or 2. int max = 2324; or 3. Use equals() method of Integer class.

Related

Converting from Integer wrapper class to int primitive class

I've been trying to convert an Integer Wrapper class to int primitive class. I haven't yet found a proper way to make the code compile. I'm using Intellij IDEA, Java 11 Amazon Coretto, but I need to run it on a computer that runs java 8.
Here's the original code below:
static class Line<Integer> extends ArrayList<Integer> implements Comparable<Line<Integer>> {
#Override
public int compareTo(Line<Integer> other) {
int len = Math.min(this.size(), other.size());
for (int i = 0; i < len; i++) {;
if ((int) this.get(i) != (int) other.get(i)) {
if ((int this.get(i) < (int) this.get(i)) {
return -1;
} else if ((int) this.get(i) > (int)this.get(i)) {
return 1;
} else {}
}
}
...
note that the Line is inserted to an ArrayList.
Originally I used forced casting on all the Integer objects so it'll be like (int) this.get(i). It worked on my local terminal and my Intellij wasn't bothered about it, but unfortunately not the other computer. It couldn't compile there
I thought it was because of the forced casting, since the other computer returned
Main.java:159: error: incompatible types: Integer cannot be converted to int
if ((int) this.get(i) != (int) other.get(i)) {
^
where Integer is a type-variable:
Integer extends Object declared in class Line
so I deleted them all and thought I could let the machine unbox the Integer wrapper on its own. It still didn't compile.
If the code is left like what's written above (no forced casting), it will return "Operator '<' not applicable for 'Integer', 'Integer'"
So I used the .compareTo() method. Compile error.
Then I tried to assign them to an int variable. Intellij IDEA was screaming at me that it required int but found Integer instead. So I force-casted, like so
int thisLine = (int) this.get(i);
int otherLine = (int) other.get(i);
if (thisLine != otherLine) {
if (thisLine < otherLine) {
return -1;
} else if (thisLine > otherLine) {
return 1;
} else {}
Nope, didn't work. Removing the cast also didn't work.
I looked up the Javadocs (https://docs.oracle.com/javase/8/docs/api/java/lang/Integer.html#intValue--) this time about the Integer class and found a promising little method called intValue(). Problem is? Intellij cannot resolve that method (oddly, VSCode does not consider this an error). I used it like this
int thisLine = this.get(i).intValue();
int otherLine = other.get(i).intValue();
if (this.get(i) != other.get(i)) {
if (thisLine < otherLine) {
return -1;
} else if (thisLine > otherLine) {
return 1;
and sure enough, another compile error on that stubborn computer.
I'm running out of options. I'm seriously considering creating a new custom class just so I can store int values in an ArrayList without having to deal with all this Java backwards incompatibility nonsense.
Anyone here know a consistent method for converting an Integer wrapper object to an int primitive object in Java?
This is the clue in the error message that explains it:
where Integer is a type-variable:
Integer extends Object declared in class Line
Integer is not java.lang.Integer but a type variable with a confusing name...
You declared the type variable here:
static class Line<Integer> extends ArrayList<Integer> implements Comparable<Line<Integer>>
It's as if you declared it like this:
static class Line<T> extends ArrayList<T> implements Comparable<Line<T>>
but by naming the type variable Integer instead of T, and then you try to cast objects of the type T to int later on.
Fix it by not declaring a type parameter named Integer, you don't need that here:
static class Line extends ArrayList<Integer> implements Comparable<Line<Integer>>
You shouldn't have to cast an Integer to an int at all. Integer class has .compareTo methods which compare two integers.
A 0 means value1 is equal to value2. -1 is value1 is less than value2 and a 1 is value1 is greater than value2.
Try the following:
public int compareTo(Line<Integer> other) {
//get the smallest length
int len = this.size() <= other.size() ? this.size() : other.size();
for (int i = 0; i < len; i++) {
int compare = this.get(i).compareTo(other.get(i));
if (compare != 0) { //if compare is not zero they are not the same value
return compare;
}
}
//If we get here, everything in both lists are the same up to "len"
return 0;
}
The compareTo() method is a method of Integer class under java. lang
package. ... It returns the result of the value 0 if Integer is equal
to the argument Integer, a value less than 0 if Integer is less than
the argument Integer and a value greater than 0 if Integer is greater
than the argument Integer.
In you class "Integer" is not a java.lang.Integer but a Generic class that is the reason

why "==" working differently for integer and strings reference? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
May I know how == works here?
public class App {
public static void main(String[] args) {
String s1 = new String("str");
String s2 = new String("str");
System.err.println("why it,s "+String.valueOf(s1==s2));
int i1 = new Integer(10);
int i2 = new Integer(10);
System.err.println("why it,s "+String.valueOf(i1==i2));
}
}
When I am comparing references of two different String with the same values, then == says that they are not equal, but when I am comparing references of two integers with the same values, then == says that they are equal. Why is it so?
Ok, a more meaningful compare would be
public class App{
public static void main(String[] args) {
String s1 = new String("str");
String s2 = new String("str");
System.err.println("why it,s "+String.valueOf(s1==s2));
Integer i1 = new Integer(10);
Integer i2 = new Integer(10);
System.err.println("why it,s "+String.valueOf(i1==i2));
}
}
int is primitive, and == will just compare the value. Integer is an object, and == for objects is only true if it points to the same place in memory, otherwise it will be false. For primitives (int, boolean, etc...) == will test the value.
int i = Integer(10) is really int i = (Integer(10)).intValue(), java just does it automagically.
Edited to add more explanation:
Java has 2 types of types. Primitive types and Class types. A primitive type is just the value of the type: an int primitive type is just that, and int. There are not methods or anything, it just is an int.
If you say int a = 4, a is a primitive variable that points to a memory address that contains an int. That's it.
A Class type is a java object, so Integer is a class type. It represents an integer value, so Integer a = new Integer(4) would create an integer object, and a would point to a memory location that contains the object that new... created.
What's different?
Good question. In the latter example (new Integer(4)) this is an integer and some other stuff, stuff like a toString() method and some other stuff.
So, a recap:
A primitive is a value stored in memory somewhere.
A class is an object stored in memory somewhere, and in the case of Integer it represents an int but it has some other stuff associated with it (i.e. the `toString() method).
Now, == is a test for equivalency. So int == int checks to see if the primitive value is the same, since that is the only information that a primitive type has.
== for objects does mean something. Since an object points to a more than just a 4 or 8 or -1, the == only returns true if the object variables point to the same place in memory. If it does not, then you get false.
So:
int i = 1;
int j = 1;
Integer k = new Integer(1)
Integer l = new Integer(1)
Integer m = k;
Integer n = new Integer(k)
i == j -> true
k == l -> false
k == k -> true
k == l -> true
n == m -> false
n.intValue() == m.intValue() -> true (intValue returns a primitive type)
Now, .equals is a test to see if two objects are equal, which means different things for different objects.
For an Integer, a.equals(b) is true if the intValue()s are the same for a and b. However, a == b is true if a and b point at the same object in memory
Now, thing about an object that has 2 integers in it (like an x,y coordinate).

Java ArrayList get() as Integer rather than Object

new to Java. Trying to understand the point of declaring my ArrayList as an <Integer>. I still have to cast my .get() result as an int in my methods for it to work, else it still returns an Object. eg: (int) deliv.get(j) int the Sort method's for loop. Is there a way to avoid this or is my code the correct approach?
Problem: Assume the array can change size, hence not just using primitive array. All numbers should be pairs, looking for the unique one missing it's pair value. I sort the array, then cycle through the pairs to look for a mismatch. Thanks.
import java.util.*;
class StolenDrone{
public static void main(String[] args){
ArrayList<Integer> deliv_id = new ArrayList<>();
deliv_id.add(99);
deliv_id.add(13);
deliv_id.add(4);
deliv_id.add(5);
deliv_id.add(8);
deliv_id.add(99);
deliv_id.add(8);
deliv_id.add(5);
deliv_id.add(4);
System.out.println("Array is: " + deliv_id);
sort(deliv_id);
System.out.println("Array is: " + deliv_id);
int unique = findUnique(deliv_id);
System.out.println("Unique ID is: " + unique);
}
//Sort ArrayList into increasing order
static void sort(ArrayList deliv){
int temp;
for(int i = 0; i<deliv.size();i++){
for (int j=0; j<deliv.size()-1;j++){
if((int) deliv.get(j)> (int) deliv.get(j+1)){
temp = (int) deliv.get(j+1);
deliv.set(j+1, deliv.get(j));
deliv.set(j, temp);
}
}
}
}
//check pairs in ArrayList to find unique entry
static int findUnique(ArrayList deliv){
for(int i = 0; i<deliv.size()-1;i+=2){
if(deliv.get(i) == null){
return -1; //no unique
}
if((int) deliv.get(i) != (int) deliv.get(i+1)){
return (int) deliv.get(i);
}
}
return -1;
}
}
When you type parameterize ArrayList<Integer> the compiler knows that everything inside the ArrayList is of type Integer and will only allow you to add Integers to the list, and thus get() returns Integer. Without parameterizing the compiler will allow you to add any Object to the ArrayList, and thus calling get() will return an Object and requiring the cast to int.
To remove the need for casts you need to change parameters with type ArrayList to ArrayList<Integer> in the function declaration.
static void sort(ArrayList deliv)
Your method signature requests an untyped ArrayList.
The compiler cannot know what will be inside the ArrayList so it requires you to cast the result.
Change it to this:
static void sort(ArrayList<Integer> deliv)
Now the compiler knows it is an ArrayList of Integers.
So you wont need to add the cast to get()
In Java Integet is wrapper-class of int. You cannot set int as a type of ArrayList to work, but you can put there int type and it will be automatticly casted to Integer. To meke work it good you should do like this :
static void sort(ArrayList deliv){
int temp;
for(int i = 0; i<deliv.size();i++){
for (int j=0; j<deliv.size()-1;j++){
if(deliv.get(j)> deliv.get(j+1)){ // You should not cast, Integer is Comparable
temp = deliv.get(j+1).intValue();//Changes here
deliv.set(j+1, deliv.get(j).intValue());//And here
deliv.set(j, temp);
}
}
}
}
Good luck

What does it mean to return a reference to an array?

I was doing some exercises on arrays, and I was prompted to return a reference to an array after copying it element by element. What does this exactly mean?
My code is the following:
public static int[] cloneArray(int array[])
{
int[] arraycopy = new int[array.length];
for(int i = 0; i < array.length; i++)
{
arraycopy[i] = array[i];
}
return arraycopy;
}
I don't know what I should be returning though as a "reference": should I return an array of ints or an int? Whenever I try to print the array, I get a weird combination of characters and numbers (unless I invoke Arrays.toString()).
"Return a reference to an array" just means "return an array".
Java only returns values, which are either primitives or object references (ie for objects, the value is a reference).
Although Java is based on C, it doesn't sully itself with pointers etc like C does.
In Java, arrays and objects do not act like primitive types such as int. Consider the following code:
public class MyClass {
public static int method1(int ar[]) {
int x = ar[1];
ar[1] = 3;
return x;
}
}
Now suppose that somewhere else, the follow code is executed:
int abcd[] = new int[3];
abcd[0] = 0;
abcd[1] = 1;
abcd[2] = 2;
int d = MyClass.method1(abcd);
System.out.println(abcd[1]);
What would be printed? It's not 1, but 3. This is because the method was not given the data in the array, it was told the location of the array. In other words, it was passed a reference. Because it was using a reference, changing the value of an array index changed its value in the code that called it. This would not have happened if method1 had taken an int as an argument.
Basically, in Java, methods do not accept arrays as arguments or return arrays. They only use references to arrays. The same goes for objects (except for Strings, which are passed by value).
In Java, Objects are only accessed by reference. Just return the Array object.

How to cast an Object to an int

How can I cast an Object to an int in java?
If you're sure that this object is an Integer :
int i = (Integer) object;
Or, starting from Java 7, you can equivalently write:
int i = (int) object;
Beware, it can throw a ClassCastException if your object isn't an Integer and a NullPointerException if your object is null.
This way you assume that your Object is an Integer (the wrapped int) and you unbox it into an int.
int is a primitive so it can't be stored as an Object, the only way is to have an int considered/boxed as an Integer then stored as an Object.
If your object is a String, then you can use the Integer.valueOf() method to convert it into a simple int :
int i = Integer.valueOf((String) object);
It can throw a NumberFormatException if your object isn't really a String with an integer as content.
Resources :
Oracle.com - Autoboxing
Oracle.com - Primitive Data types
On the same topic :
Java: What's the difference between autoboxing and casting?
Autoboxing: So I can write: Integer i = 0; instead of: Integer i = new Integer(0);
Convert Object into primitive int
Scenario 1: simple case
If it's guaranteed that your object is an Integer, this is the simple way:
int x = (Integer)yourObject;
Scenario 2: any numerical object
In Java Integer, Long, BigInteger etc. all implement the Number interface which has a method named intValue. Any other custom types with a numerical aspect should also implement Number (for example: Age implements Number). So you can:
int x = ((Number)yourObject).intValue();
Scenario 3: parse numerical text
When you accept user input from command line (or text field etc.) you get it as a String. In this case you can use Integer.parseInt(String string):
String input = someBuffer.readLine();
int x = Integer.parseInt(input);
If you get input as Object, you can use (String)input, or, if it can have an other textual type, input.toString():
int x = Integer.parseInt(input.toString());
Scenario 4: identity hash
In Java there are no pointers. However Object has a pointer-like default implementation for hashCode(), which is directly available via System.identityHashCode(Object o). So you can:
int x = System.identityHashCode(yourObject);
Note that this is not a real pointer value. Objects' memory address can be changed by the JVM while their identity hashes are keeping. Also, two living objects can have the same identity hash.
You can also use object.hashCode(), but it can be type specific.
Scenario 5: unique index
In same cases you need a unique index for each object, like to auto incremented ID values in a database table (and unlike to identity hash which is not unique). A simple sample implementation for this:
class ObjectIndexer {
private int index = 0;
private Map<Object, Integer> map = new WeakHashMap<>();
// or:
// new WeakIdentityHashMap<>();
public int indexFor(Object object) {
if (map.containsKey(object)) {
return map.get(object);
} else {
index++;
map.put(object, index);
return index;
}
}
}
Usage:
ObjectIndexer indexer = new ObjectIndexer();
int x = indexer.indexFor(yourObject); // 1
int y = indexer.indexFor(new Object()); // 2
int z = indexer.indexFor(yourObject); // 1
Scenario 6: enum member
In Java enum members aren't integers but full featured objects (unlike C/C++, for example). Probably there is never a need to convert an enum object to int, however Java automatically associates an index number to each enum member. This index can be accessed via Enum.ordinal(), for example:
enum Foo { BAR, BAZ, QUX }
// ...
Object baz = Foo.BAZ;
int index = ((Enum)baz).ordinal(); // 1
Assuming the object is an Integer object, then you can do this:
int i = ((Integer) obj).intValue();
If the object isn't an Integer object, then you have to detect the type and convert it based on its type.
#Deprecated
public static int toInt(Object obj)
{
if (obj instanceof String)
{
return Integer.parseInt((String) obj);
} else if (obj instanceof Number)
{
return ((Number) obj).intValue();
} else
{
String toString = obj.toString();
if (toString.matches("-?\d+"))
{
return Integer.parseInt(toString);
}
throw new IllegalArgumentException("This Object doesn't represent an int");
}
}
As you can see, this isn't a very efficient way of doing it. You simply have to be sure of what kind of object you have. Then convert it to an int the right way.
You have to cast it to an Integer (int's wrapper class). You can then use Integer's intValue() method to obtain the inner int.
Answer:
int i = ( Integer ) yourObject;
If, your object is an integer already, it will run smoothly. ie:
Object yourObject = 1;
// cast here
or
Object yourObject = new Integer(1);
// cast here
etc.
If your object is anything else, you would need to convert it ( if possible ) to an int first:
String s = "1";
Object yourObject = Integer.parseInt(s);
// cast here
Or
String s = "1";
Object yourObject = Integer.valueOf( s );
// cast here
I use a one-liner when processing data from GSON:
int i = object != null ? Double.valueOf(object.toString()).intValue() : 0;
If the Object was originally been instantiated as an Integer, then you can downcast it to an int using the cast operator (Subtype).
Object object = new Integer(10);
int i = (Integer) object;
Note that this only works when you're using at least Java 1.5 with autoboxing feature, otherwise you have to declare i as Integer instead and then call intValue() on it.
But if it initially wasn't created as an Integer at all, then you can't downcast like that. It would result in a ClassCastException with the original classname in the message. If the object's toString() representation as obtained by String#valueOf() denotes a syntactically valid integer number (e.g. digits only, if necessary with a minus sign in front), then you can use Integer#valueOf() or new Integer() for this.
Object object = "10";
int i = Integer.valueOf(String.valueOf(object));
See also:
Inheritance and casting tutorial
int i = (Integer) object; //Type is Integer.
int i = Integer.parseInt((String)object); //Type is String.
Can't be done. An int is not an object, it's a primitive type. You can cast it to Integer, then get the int.
Integer i = (Integer) o; // throws ClassCastException if o.getClass() != Integer.class
int num = i; //Java 1.5 or higher
You can't. An int is not an Object.
Integer is an Object though, but I doubt that's what you mean.
If you mean cast a String to int, use Integer.valueOf("123").
You can't cast most other Objects to int though, because they wont have an int value. E.g. an XmlDocument has no int value.
I guess you're wondering why C or C++ lets you manipulate an object pointer like a number, but you can't manipulate an object reference in Java the same way.
Object references in Java aren't like pointers in C or C++... Pointers basically are integers and you can manipulate them like any other int. References are intentionally a more concrete abstraction and cannot be manipulated the way pointers can.
int[] getAdminIDList(String tableName, String attributeName, int value) throws SQLException {
ArrayList list = null;
Statement statement = conn.createStatement();
ResultSet result = statement.executeQuery("SELECT admin_id FROM " + tableName + " WHERE " + attributeName + "='" + value + "'");
while (result.next()) {
list.add(result.getInt(1));
}
statement.close();
int id[] = new int[list.size()];
for (int i = 0; i < id.length; i++) {
try {
id[i] = ((Integer) list.get(i)).intValue();
} catch(NullPointerException ne) {
} catch(ClassCastException ch) {}
}
return id;
}
// enter code here
This code shows why ArrayList is important and why we use it. Simply casting int from Object. May be its helpful.
For Example Object variable; hastaId
Object hastaId = session.getAttribute("hastaID");
For Example Cast an Object to an int,hastaID
int hastaID=Integer.parseInt(String.valueOf(hastaId));
Refer This code:
public class sample
{
public static void main(String[] args)
{
Object obj=new Object();
int a=10,b=0;
obj=a;
b=(int)obj;
System.out.println("Object="+obj+"\nB="+b);
}
}
so divide1=me.getValue()/2;
int divide1 = (Integer) me.getValue()/2;
We could cast an object to Integer in Java using below code.
int value = Integer.parseInt(object.toString());
If you want to convert string-object into integer...
you can simply pass as:
int id = Integer.valueOf((String) object_name);
Hope this will be helpful :-)
Integer x = 11
int y = x.intValue();
System.out.println("int value"+ y);
Finally, the best implementation for your specification was found.
public int tellMyNumber(Object any) {
return 42;
}
first check with instanceof keyword . if true then cast it.

Categories