0

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 
1
  • 1
    you are not creating new object, you are updating existing object. Create new object every time. Commented May 27, 2022 at 5:11

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

Could u tell me now how to use a specific variable from a specific obj n the list????
ArrayList ::get Please also consider to accept and upvote my answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.