Results 1 to 3 of 3
Thread: Help ArrayList.add()
- 08-06-2007, 01:42 AM #1
Member
- Join Date
- Aug 2007
- Location
- new yrok
- Posts
- 3
- Rep Power
- 0
Help ArrayList.add()
Can someone please tellme what is wrong with my code? I'm new Java but I haven't had any trouble with ArrayList until I tried to write the code below. For some reason, the Rectangle2D 's are not being added to my arrayList.
import java.util.ArrayList;
import java.awt.geom.Rectangle2D;
public class Hat {
ArrayList<Rectangle2D.Double> rectangles = new ArrayList<Rectangle2D.Double>(5);
public Hat(){
}
Hat(double x, double y, double w, double h){
rectangles.add((new Rectangle2D.Double(x,y,w,h) ) );
}
public void countHats(){
System.out.println("There are "+ rectangles.size() +" in list");
}
public static void main(String[] args){
Hat h = new Hat();
int limit =5;
int randomLim = 100;
for(int i=0;i<limit;i++)
{
new Hat(Math.random()*randomLim,Math.random()*randomLi m,Math.random()*randomLim,Math.random()*randomLim) ;
}
h.countHats();
}
}
- 08-06-2007, 04:34 AM #2
You made a new Hat each time with only one rectangle in the ArrayList of the Hat for each trip through the for loop. So you ended up with 5 Hats. Instead, make an add method so you can add rectangles to any Hat. Then you can have a Hat with multiple rectangles. In your h.countHats() statement you get zero because you never did anything with the Hat h you created before the for loop. Try this:
Java Code:import java.util.ArrayList; import java.awt.geom.Rectangle2D; public class HatRx { ArrayList<Rectangle2D.Double> rectangles = new ArrayList<Rectangle2D.Double>(5); public HatRx(){} void add(double x, double y, double w, double h){ rectangles.add((new Rectangle2D.Double(x,y,w,h) ) ); } public void countHats(){ System.out.println("There are "+ rectangles.size() +" in list"); } public static void main(String[] args){ HatRx h = new HatRx(); int limit =5; int randomLim = 100; for(int i = 0; i < limit; i++) { h.add( Math.random()*randomLim, Math.random()*randomLim, Math.random()*randomLim, Math.random()*randomLim); } h.countHats(); } }
- 08-06-2007, 01:13 PM #3
Member
- Join Date
- Aug 2007
- Location
- new yrok
- Posts
- 3
- Rep Power
- 0
Similar Threads
-
Java Project Trouble: Searching one ArrayList with another ArrayList
By BC2210 in forum New To JavaReplies: 2Last Post: 04-21-2008, 11:43 AM -
ArrayList
By ramitmehra123 in forum New To JavaReplies: 1Last Post: 02-07-2008, 12:47 AM -
ArrayList
By kizilbas1 in forum New To JavaReplies: 1Last Post: 01-12-2008, 08:48 PM -
ArrayList
By kizilbas1 in forum New To JavaReplies: 11Last Post: 12-05-2007, 07:30 PM -
New to arraylist
By kleave in forum New To JavaReplies: 2Last Post: 11-19-2007, 06:45 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks