?
Solved

Accessing an ArrayList from another class - Java

Posted on 2011-10-29
25
Medium Priority
?
643 Views
Last Modified: 2013-11-23
I'm working on a Java project and I'm trying to use an ArrayList to hold objects (a "beeper") with their own properties (int x, int y).  So, I have in main:
 
public class geisrud {
	
	public static void main (String[] args){
		//ArrayList<beeper> bArray = new ArrayList<beeper>();
		
		world World1 = new world(beeper.bArray);  //new world object "World1" using bArray
		
		UrRobot Robot1 = new UrRobot (1, 1, "East", 0, true, World1); 
				//robot is at 1st, 1av, 0 beepers, on, and using World1
		
		
		beeper beeper1 = new beeper (1, 2);  //some beeper objects
		beeper beeper2 = new beeper (1, 2);
		beeper beeper3 = new beeper (1, 3);
		
		
		beeper.bArray.add(beeper1);   //add a few beepers to bArray
		beeper.bArray.add(beeper2);
		beeper.bArray.add(beeper3);

		Robot1.move();
		Robot1.display();
		Robot1.pickBeeper();
		Robot1.display();
 }
}

Open in new window


In another class, I have a method where I want to check to see if my robot's location contains a beeper.  So he needs to check the ArrayList for an object with those properties...(hopefully you get what I'm trying to do here....it obviously doesn't work:
 
public int pickBeeper(){				
		if (status != false){							//check if the robot is not turned off
				if (World1.bArray.contains(street, avenue){
					beeperCount++;
					World1.bArray.remove(street, avenue);
					
					}									//increases beeper count by one if the robot is on
			return beeperCount;							//returns the beepercount
		}
}

Open in new window


Can someone help me along with how to check the ArrayList, and ask it, "is there an [any] object(s) at (x, y)?

Much obliged
0
Comment
Question by:Geisrud
  • 18
  • 7
25 Comments
 
LVL 47

Expert Comment

by:for_yan
ID: 37051568
In order to use contains method - you should be sure that your class bBeeper has equals method defined the way you need it tio be derfined
0
 
LVL 47

Expert Comment

by:for_yan
ID: 37051569
Post your beeper class
0
 
LVL 47

Expert Comment

by:for_yan
ID: 37051576
I guess in your case the mthod should be something like that
(assuming that you have these getX() getY() methods in beeper class
public boolean Object equals(Object o) {

beeper b = (beeper) o;
if(b.get.getX() == this.X && b.getY() = this.Y)return true;
else return false;


}

Open in new window

0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 14

Author Comment

by:Geisrud
ID: 37051580
Here's my beeper class:
import java.util.ArrayList;

	public class beeper{
		int street;
		int avenue;
		
		//constructor for a beeper object
		public beeper(int s, int a){
		street = s;				//street and avenue for location
		avenue = a;
	
		}
		public static ArrayList<beeper> bArray = new ArrayList<beeper>(); 
	}

Open in new window

0
 
LVL 47

Expert Comment

by:for_yan
ID: 37051585
You need to add method boolean equals(Object o) like below:

import java.util.ArrayList;

	public class beeper{
		int street;
		int avenue;
		
		//constructor for a beeper object
		public beeper(int s, int a){
		street = s;				//street and avenue for location
		avenue = a;
	
		}
             
public boolean equals(Object o) {

beeper b = (beeper) o;
if(b.street == this.street && b.avenue = this.avenue)return true;
else return false;


}


		public static ArrayList<beeper> bArray = new ArrayList<beeper>(); 
	}

Open in new window

0
 
LVL 47

Assisted Solution

by:for_yan
for_yan earned 2000 total points
ID: 37051586
small correction:

import java.util.ArrayList;

	public class beeper{
		int street;
		int avenue;
		
		//constructor for a beeper object
		public beeper(int s, int a){
		street = s;				//street and avenue for location
		avenue = a;
	
		}
             
public boolean equals(Object o) {

beeper b = (beeper) o;
if(b.street == this.street && b.avenue == this.avenue)return true;
else return false;


}


		public static ArrayList<beeper> bArray = new ArrayList<beeper>(); 
	}

Open in new window

0
 
LVL 47

Expert Comment

by:for_yan
ID: 37051591
Other points:
you want usually to name your classes with upper case - llike Beeper, not beeper

You usually don't want to use like that b.street, b.avenue
and more common evven to defibne these variables private
and have public methods

public int getStreet() { return street; }
etc.

0
 
LVL 47

Expert Comment

by:for_yan
ID: 37051596
Whenm you add your beeper instance to your array list you need the new statement to create an instance, like that, using your nnamings:

public static ArrayList<beeper> bArray = new ArrayList<beeper>(); 
bArray.add(new beeper(1,2));

Open in new window


0
 
LVL 47

Expert Comment

by:for_yan
ID: 37051602
Maybe you want to think about defining in beeper only waht relates to one beeper - so taht instance of the class will corresponsd to actual object itself
and then have other classes which would manipulate with many beepers and which would deal with ArrayLists of beepers
rather than to declare static ArrayList of beepers within class beeper itself.
This last thing is by no means any  law of course - it is legal to dom it the way you do
and in some cases quaite justified fomr the logical point of view - all depends on the big picture of your design, this is just what comes to my
mind
0
 
LVL 47

Expert Comment

by:for_yan
ID: 37051610
ArrayList will need to use the method equals(Object o) f your class in order to
execute such methods as contains(beeper b) or remove(beeper b)
Otherwise it would not be able to determine if the object which you want to remove or for which you are checking
is present in the  ArrayList
0
 
LVL 14

Author Comment

by:Geisrud
ID: 37051614
Wow - a lot of info - I can't keep up!
I'll have to digest it a little at a time.

Just regarding my original question though, can you help me with how do I communicate with the array?  Nothing I try seems to work...
if (World1.bArray.contains(street, avenue){
      beeperCount++;
      World1.bArray.remove(street, avenue);
				
}

Open in new window


And your last code:
public static ArrayList<beeper> bArray = new ArrayList<beeper>();
bArray.add(new beeper(1,2));

does that go in main, or my beeper class, or somewhere else?

0
 
LVL 47

Expert Comment

by:for_yan
ID: 37051619
That piece

public static ArrayList<beeper> bArray = new ArrayList<beeper>();
bArray.add(new beeper(1,2));
 is basically what you are doing here - this is right
I should not have posted that

beeper beeper1 = new beeper (1, 2);  //some beeper objects
		beeper beeper2 = new beeper (1, 2);
		beeper beeper3 = new beeper (1, 3);
		
		
		beeper.bArray.add(beeper1);   //add a few beepers to bArray
		beeper.bArray.add(beeper2);
		beeper.bArray.add(beeper3);

Open in new window

0
 
LVL 47

Expert Comment

by:for_yan
ID: 37051623

what was not right, and prompted me to post the adding stuff, was here:

bArray.contains(street, avenue){

when you want to check conatuins you should also dell with instance of beeper, not with strets and avenues themsleves:

so this piece should be:

if (bArray.contains(new beeper(street, avenue)) {....

not just

if(bArray.contains(street, avenue)){...

0
 
LVL 14

Author Comment

by:Geisrud
ID: 37051627
but I just want the (street, avenue) pair.  There may be more than one beeper at the same location.

for example, I may have
beeper beeper1 = new beeper (1, 2);  //some beeper objects
beeper beeper2 = new beeper (1, 2);
beeper beeper3 = new beeper (1, 3);

Open in new window


the robot needs to just find one, and have the rest remain.
0
 
LVL 47

Expert Comment

by:for_yan
ID: 37051631
Well that measn that your beeper objects at least the way you defined them in your array are not unique.
That will not be a problem with contains method - it will return true if there is at least one beeper with such parameters,

Howvere let us check the API what will do remove() method in such environement
0
 
LVL 47

Expert Comment

by:for_yan
ID: 37051633
OK, you'd be fine. remove() method will remove only one of
the matching elements if there are more than one equal beepers:

http://download.oracle.com/javase/6/docs/api/java/util/ArrayList.html#remove%28java.lang.Object%29

public boolean remove(Object o)

    Removes the first occurrence of the specified element from this list, if it is present. If the list does not contain the element, it is unchanged. More formally, removes the element with the lowest index i such that (o==null ? get(i)==null : o.equals(get(i))) (if such an element exists). Returns true if this list contained the specified element (or equivalently, if this list changed as a result of the call).
0
 
LVL 14

Author Comment

by:Geisrud
ID: 37051634
I think I see.  So if should write this to populate my ArrayList
 
bArray.add(new beeper(1, 2));   //add a few beepers to bArray
bArray.add(new beeper(1, 2));
bArray.add(new beeper(1, 3));

Open in new window

0
 
LVL 47

Expert Comment

by:for_yan
ID: 37051637
yes this is correct

And Id'  probably still try to design it so that my ArrayList would live in some other class - not in the beeper itslef.

And if you are sure that you want to have only onee such arraylist in your whol application then it makes sense indded
to make this arraylist static
0
 
LVL 14

Author Comment

by:Geisrud
ID: 37051641
I will actually have three ArrayLists.  I'm just trying to get this one working first.
0
 
LVL 47

Expert Comment

by:for_yan
ID: 37051642
one small correction to my previous post about equals() method

The class beeper should be a little bit moere general if we modify that method like this:

public boolean equals(Object o) {

if( !(o instanceof beeper)) return false;
beeper b = (beeper) o;
if(b.street == this.street && b.avenue == this.avenue)return true;
else return false;


}

Open in new window


in this way if someone decises to run equals() on the object which is not beeper they'll not get exception
0
 
LVL 47

Expert Comment

by:for_yan
ID: 37051645
Anyway, you should know better
Just need to understand that if you have some class and some filed
defined in this class - then in normal situation each instance of your class will have this fields with its own value.
If you declare the filed static - tha means that all instances of this class in your application will
acutally share  this field - which will be in fact unique in your application.


0
 
LVL 14

Author Comment

by:Geisrud
ID: 37051676
Yeah - I know I need to tweak the access modifiers.  I was just keeping things open until I got everything working.

I think I'm getting close with checking the array for a beeper at an intersection (street, avenue) - but I can't figure it out.
 
if (beeper.bArray.equals(street) && beeper.bArray.equals(avenue)){
	beeperCount++;
        beeper.bArray.remove(beeper(street, avenue));
}

Open in new window

0
 
LVL 47

Accepted Solution

by:
for_yan earned 2000 total points
ID: 37051689
this should be
beeper.bArray.remove(new beeper(street, avenue));

you need to say "new" as you need to create instance (execute constructor) and specify that this isnatnce should be removed



This is is incorrect:
beeper.bArray.equals(street) && beeper.bArray.equals(avenue)

I guess you want to check if bArray conatins some particular instance of a beeper, so you need to
do it in this way:

if(beeper.bArray.contains(new beeper(street, avenue)) {

in oprder to use conatinas() method for ArrayList made out of elements of type beeper
you ned the class beeper to implement method equals(Object o)
that does not mean that you need explicilty to mention this method
ArrayList will invoke this method itself when executing method
contains(beeeper b)



 
0
 
LVL 14

Author Comment

by:Geisrud
ID: 37051701
Perfect.
 
if (beeper.bArray.contains(new beeper(street, avenue))){
	beeperCount++;
	beeper.bArray.remove(new beeper(street, avenue));

}

Open in new window


Thank you so much for all your help this evening!
0
 
LVL 47

Expert Comment

by:for_yan
ID: 37051704
You are alwyas welcome.
This last piece is absolutely correct.
I see, sounds a little bit odd - you create with "new" just to remove
but once you think about it - it makes good sense
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.
Suggested Courses
Course of the Month13 days, 23 hours left to enroll

807 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question