Java ArrayList get () as a whole, not an Object

new to java. Trying to understand the meaning of my declaration of ArrayListhow <Integer>. I still need to give my result .get()as intin my methods for it to work, otherwise it returns anyway Object. for example: (int) deliv.get(j)int sorting loop for. Is there a way to avoid this, or is my code the correct approach?

Problem: suppose an array can resize, therefore, not only using a primitive array. All numbers must be pairs, looking for the only one that does not have the value of a pair. I sort the array and then iterate over the pairs to look for a mismatch. Thank.

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

}
+4
source share
3 answers

static void sort(ArrayList deliv)

ArrayList. , ArrayList, , .

:

static void sort(ArrayList<Integer> deliv)

, ArrayList . get()

+2

izeize ArrayList<Integer>, , ArrayList Integer Integers , , , get() Integer. Object ArrayList, , , get() Object , int.

, ArrayList ArrayList<Integer> .

+4

Java Integet has an int wrapper class. You cannot set int as an ArrayList type to work, but you can put an int type in there, and it will be automatically superimposed on Integer. For meke to work well, 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.

+2
source

Source: https://habr.com/ru/post/1583986/


All Articles