0

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......

2
  • 4
    public class Balloons implements Balloon { public void Balloon(...: are you engaged in an obfuscation contest or what? Don't use the same name for everything. And respect the Java naming conventions. Commented Nov 3, 2013 at 15:30
  • Noted. I have been told about that before by my professor. Bit of a nasty habit sorry. Commented Nov 3, 2013 at 15:46

2 Answers 2

3

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:

Sign up to request clarification or add additional context in comments.

2 Comments

This fixed the problem I had with adding an object to the array thank you. How would I then retrieve the area of the balloon from a specified position in the array?
@user2950071 a.get(someIndex).getArea().
2

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;
            }
        });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.