Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java put different objects in the same arrayList

I have a Airport class where I built the airport object. Now, I am trying to put different objects in the same array but without changing the object name every single time.
The problem is that my program will only get the last object instead of getting all of them.
”’
public class Main {

public static void main(String[] args)
{
    ArrayList <Airport> myAl = new ArrayList();
    Airport obj = new Airport();
    int i = -1;
    obj.setValues(++i, "Wright-Patterson Air Force Base", "OH", 39.819527, -84.067406, 0);
    myAl.add(obj);
    obj.setValues(++i, "John F. Kennedy International Airport", "NY",40.641766 , -73.780968,0);
    myAl.add(obj);
    obj.setValues(++i, "Charlotte Douglas International Airport", "NC", 35.213890, -80.943054, 0);
    myAl.add(obj);
    obj.setValues(++i, "O’Hare International Airport", " IL", 41.978611, -87.904724, 0);
    myAl.add(obj);
    obj.setValues(++i, "Tucson International Airport", "AZ", 32.116112, -110.941109, 0);
    myAl.add(obj);

    Airport xx = new Airport();
    for(i =0; i<myAl.size();i++)
    {
        xx = myAl.get(i);
        System.out.print(xx.getId() +" " + xx.getFullName()+"\n");
    }


}}

”’
Output

4 Tucson International Airport AZ 
4 Tucson International Airport AZ 
4 Tucson International Airport AZ 
4 Tucson International Airport AZ 
4 Tucson International Airport AZ 

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Create a new Object first

ArrayList <Airport> myAl = new ArrayList();
Airport obj = new Airport();
int i = -1;
obj.setValues(++i, "Wright-Patterson Air Force Base", "OH", 39.819527, -84.067406, 0);
myAl.add(obj);

obj = new Airport();
obj.setValues(++i, "John F. Kennedy International Airport", "NY",40.641766 , -73.780968,0);
myAl.add(obj);

obj = new Airport();
obj.setValues(++i, "Charlotte Douglas International Airport", "NC", 35.213890, -80.943054, 0);
myAl.add(obj);

obj = new Airport();
obj.setValues(++i, "O’Hare International Airport", " IL", 41.978611, -87.904724, 0);
myAl.add(obj);

// etc
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading