简体   繁体   中英

How to retrieve index of ArrayList (Java)?

I'm trying to retrieve the first index of an ArrayList, and I can't figure out the syntax.

Snippet of DateSet Class

public class DateSet {

    public List<Date> dates; 

    public DateSet() {
        this.dates = new ArrayList<Date>();
    }

    public void add(Date date) {
        if (this.dates.contains(date)) {
            return;
        }
        this.dates.add(date);
    }

    public static void main(String args []) {
        DateSet setty = new DateSet();
        Date date = new Date("test");
        setty.add(date);
        setty.get(0); // < doesn't work
    }

Snippet of Date Class:

public class Date {

    String date;

    // constructor for date class
    public Date(String date) {
        this.date = date;
    }
}

I figured that since I'm creating an object "date" of type Date and add that to the ArrayList, I would need to somehow call it by calling the String inside date but I'm not quite sure if that's the case/how to do that.

Would appreciate some help, thanks in advance!

You need to obtain the reference to the dates object first.

Change

setty.get(0);

to

setty.dates.get(0);

or the following to get the date as string:

setty.dates.get(0).date

Then save it to a variable or print it like:

System.out.println(setty.dates.get(0).date);

You should use getters/setters though.

On a separate note, this.dates.contains(date) won't work unless you override equals() and hashcode() in the Date class. And if you don't want duplicates, you should use Set instead of List .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM