Question

I have a generic class that implements a "Set" using ArrayList:

public class MySet<E> {
    ArrayList <E> setList;
    public MySet(){
        this.setList =  new ArrayList<E>();
    }
    public MySet(E[] inputArray){
        this();
        for(E element: inputArray)
            insert( element);
    }
    ...

Now i have another Class "Person.java" that have properties of "age","name","ID"..

Lets say i make an array of Person[] and make an object of type set from that array:

Person p1 = new Person("dani",15,12344);
Person p2 = new Person("michal",24,12354);
Person p3 = new Person("Leah",22,18888);
Person[] PeopleArr = {p1,p2,p3};
MySet<Person> People = new  MySet<Person>(PeopleArr);

And now i want to make a generic method in Person that gets a type of MySet and returns an object of type Person that have the minimal age. How do i iterate through such thing?

I know that when passing an array its not a problem:

public static <E extends Comparable<Person> > E min (E[] array) { 
    if (array == null || array.length ==0) return null;
    E min = array[0];
    for(int i=0;i<array.length;i++){
        if(array[i].compareTo((Person) min) <0) min = array[i];
    }
    return min;
}
public int compareTo(Object persona) {
    // TODO Auto-generated method stub
    Person person = (Person) persona;
    if (this.age == person.age)
        return 0;
    else if(this.age < person.age)
        return -1;
    return 1;
}

But i want the signature to be:

public static <E extends Comparable<Person> > E min (MySet<Person> set) 

Any ideas how? (Its not possible to cast from MySet to ArrayList) Iterator seems like the only way but no idea how to compare the values

Thank you!!!

Was it helpful?

Solution

Implement Iterable interface in MySet class:

public class MySet<E> implements Iterable<E> {
    ...
    public Iterator<E> iterator() {
        return setList.iterator();
    }
}

Now you can iterate over MySet items:

for (Person person : set) {
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top