1,105,221 Community Members

Search in array of objects (?)

Member Avatar
Fotis_13
Newbie Poster
10 posts since Dec 2011
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Hi.

I cannot explain my question very well.
I have an array of objects. Can i perform a search in this?

Check the following code as example:

public class test1 {
        public static void main (String[] args){

            test2[] array = new test2[2];

            for(int i=0;i<2;i++){
            array[i]=new test2(); 
            }

            int a=1, b=2;
            String c ="c", d = "d";

            array[0].insert(a, c);
            array[1].insert(b, d);    
        }
}

and

public class test2 {    
        int z;
        String y;
    public void insert(int z, String y) { 
        this.z = z; 
        this.y = y; 
    } 
}

I want check if int 1 (or String b) exists in array[i].
Is it possible?

Member Avatar
NormR1
Posting Sage
7,723 posts since Jun 2010
Reputation Points: 563 [?]
Q&As Helped to Solve: 793 [?]
Skill Endorsements: 16 [?]
Team Colleague
 
1
 

The array: array contains only Test2 objects. It does not contain either int or String objects.
You must ask the Test2 object what it contains. Add methods to the Test2 class that will check for the contents that you want to test for. Then you can call those methods to determine the contents of a Test2 object.

Member Avatar
Fotis_13
Newbie Poster
10 posts since Dec 2011
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Ok, thanks for the reply.

But can i perform this search with a for loop in the main test1 class?

Is that possible?

Member Avatar
NormR1
Posting Sage
7,723 posts since Jun 2010
Reputation Points: 563 [?]
Q&As Helped to Solve: 793 [?]
Skill Endorsements: 16 [?]
Team Colleague
 
0
 

You can do the search in a for loop in any method that has access to the array.

Member Avatar
JamesCherrill
... trying to help
10,362 posts since Apr 2008
Reputation Points: 2,081 [?]
Q&As Helped to Solve: 1,749 [?]
Skill Endorsements: 47 [?]
Moderator
Featured
 
1
 

Sure. Suppose I had an array of Car objects, I could find the Fords with something like

for (Car c : myArrayOfCars) {
   if (c.getManufacturer().equals("Ford") ...
}
Question Answered as of 1 Year Ago by NormR1 and JamesCherrill
Member Avatar
Fotis_13
Newbie Poster
10 posts since Dec 2011
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Thanks all for the replies.

You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article