comparing objects in an ArrayList

Hi everyone!

I have an ArrayList of objects that have String parts. For example, the list contains Courses that have String names so it would be like course1.name

I need to check that a different Course being added to the list does not have the same name as one of the other courses already in the list. I tried using a for loop with Iterator but I can't get it to compare the names of the course because I can't do it.next().name

Is there a way to access the variables inside the object using a for loop?

My code is like this:

ArrayList<Course> a = new ArrayList<Course>();

a.add(aCourse);

for(Iterator it = a.iterator(); it.hasNext();)

{

if aCourse.name.compareTo(it.Next().name)) == 0)

... //rest of loop

}

Thanks.

[810 byte] By [lawngnomeninjaa] at [2007-11-26 19:05:49]
# 1

boolean foundMatch = false;

for (Course c : courses) {

if (c.name.equals(aCourse.name) {

foundMatch = true;

break;

}

}

But I'd argue a better thing would be to maintain a Map<String, Course> where the String is the course name. Then you could look it up immediately.

paulcwa at 2007-7-9 20:56:29 > top of Java-index,Java Essentials,New To Java...
# 2
If the variables are public then you can access them using the dot notation. Otherwise you will need an accessor method.
floundera at 2007-7-9 20:56:29 > top of Java-index,Java Essentials,New To Java...
# 3
Alternatively your Course class can have its own compareTo method. Then it won't matter if the name variable is private or not.
floundera at 2007-7-9 20:56:29 > top of Java-index,Java Essentials,New To Java...
# 4
Thanks paulcw. This helped a lot.
lawngnomeninjaa at 2007-7-9 20:56:29 > top of Java-index,Java Essentials,New To Java...