0

hi i want to know how i can access to elements of arraylist in java? i have this class .

class flight 
{
    public String start;
    public String end;
    public int timethatend ;
    public int timethatstart;
    flight ( int ts , int tf , String s , String e )
    {
        this.start = s;
        this.end =e;
        this.timethatend = tf;
        this.timethatstart = ts;
    }   
}

and i have this arraylist in my main class

ArrayList<flight>list = new ArrayList<flight>();

now i want print the elements of arraylist i use this syntax

System.out.println(list.get(0));

but the out put is this flight@1f96302 what should i do? another question how i can change them for example i want change the time of takeoff the first flight.

alish
  • 149
  • 2
  • 11

2 Answers2

0

This is printing the object reference to your flight object. You need to add a toString() method to your Flight class and use it to print the flight info. For example:

public String toString() {
    return start + "," + timethatstart + "," + end + "," + timethatend;
}

When you print:

System.out.println(list.get(0).toString());
Santiago Benoit
  • 994
  • 1
  • 8
  • 22
  • and how i can acess the elements for change them . for example for flight 1 i want change the time that it takeoff . what should i do? – alish Apr 01 '17 at 04:59
  • You are accessing the element with list.get(index). You can directly change its variables, for example: `list.get(0).timethatstart = 2400`, or use setter and getter methods. – Santiago Benoit Apr 01 '17 at 05:00
0

Add a toString method in the class like below:

class flight
{
    public String start;
    public String end;
    public int timethatend ;
    public int timethatstart;
    flight ( int ts , int tf , String s , String e )
    {
        this.start = s;
        this.end =e;
        this.timethatend = tf;
        this.timethatstart = ts;
    }

    @Override
    public String toString() {
        return "flight{" +
                "start='" + start + '\'' +
                ", end='" + end + '\'' +
                ", timethatend=" + timethatend +
                ", timethatstart=" + timethatstart +
                '}';
    }
}

To add new flight elements in the arraylist, to the following:

flight f = new flight(1,2,"12","34");
ArrayList<flight> list = new ArrayList<flight>();
list.add(f);

To change the value of some element, do the following:

list.get(0).start = "1234";
Pankaj Singhal
  • 15,283
  • 9
  • 47
  • 86