Reputation: 289
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!
Upvotes: 0
Views: 218
Reputation: 7917
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
.
Upvotes: 1