user2950071
user2950071

Reputation: 3

Adding objects to an arraylist using object elements

I am trying to add objects to my arraylist with which I can then implement a few methods referencing an element of the object. I have two classes Balloons and MyPark (both implement other interfaces but that's irrelavant). In the balloon class there is:

public class Balloons implements Balloon {

private int area;
private int position;

public void Balloon(int area, int position) {
    this.area = area;
    this.position = position;
}

@Override
public int getArea() {
    return area;
 }
}

And in the MyPark I have created my Arraylist of balloons:

import java.util.*;
public class MyPark implements Park {

public Balloons balloon = new Balloons;
public ArrayList <Balloon> a = new ArrayList <Balloon>();
public int index;

@Override
public void addBalloon (int barea){
   a.add(new Balloons (barea, index));
}
}

But obviously this isn't the way to do it. Any suggestions? I also want to be able to eventually sort the list by area......

Upvotes: 0

Views: 100

Answers (2)

upog
upog

Reputation: 5526

you can you comparator to sort your list

Collections.sort(SortList, new Comparator<Balloon>(){
            public int compare(Balloon b1, Balloon b2) {
                return b1.area- b2.area;
            }
        });

Upvotes: 2

Bernhard Barker
Bernhard Barker

Reputation: 55659

public void Balloon(int area, int position) isn't a constructor, it's a method - presumably you want it to be a constructor.

To make it a constructor, it should have the same name as your class (Balloons, not Balloon) and you should remove void.

public Balloons(int area, int position)

To sort the list, you basically have two options:

Upvotes: 3

Related Questions