1.11M Members

Search in array of objects (?)



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


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?


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.


Ok, thanks for the reply.

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

Is that possible?


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


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 2 Years Ago by NormR1 and JamesCherrill

Thanks all for the replies.

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