Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}

}
like image 647
Rysz Avatar asked Feb 11 '23 09:02

Rysz


1 Answers

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.

like image 172
M. Shaw Avatar answered Feb 13 '23 00:02

M. Shaw