We're a community of 1077K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,076,506 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

Search in array of objects (?)

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?

3
Contributors
5
Replies
19 Hours
Discussion Span
1 Year Ago
Last Updated
6
Views
Question
Answered
Fotis_13
Newbie Poster
10 posts since Dec 2011
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

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.

NormR1
Posting Sage
Team Colleague
7,742 posts since Jun 2010
Reputation Points: 1,158
Solved Threads: 793
Skill Endorsements: 16

Ok, thanks for the reply.

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

Is that possible?

Fotis_13
Newbie Poster
10 posts since Dec 2011
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

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

NormR1
Posting Sage
Team Colleague
7,742 posts since Jun 2010
Reputation Points: 1,158
Solved Threads: 793
Skill Endorsements: 16

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") ...
}
JamesCherrill
... trying to help
Moderator
8,533 posts since Apr 2008
Reputation Points: 2,583
Solved Threads: 1,456
Skill Endorsements: 30
Question Answered as of 1 Year Ago by NormR1 and JamesCherrill

Thanks all for the replies.

Fotis_13
Newbie Poster
10 posts since Dec 2011
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

This question has already been solved: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
 
© 2013 DaniWeb® LLC
Page rendered in 0.0752 seconds using 2.81MB