• Welcome to Overclockers Forums! Join us to reply in threads, receive reduced ads, and to customize your site experience!

Searching array of objects in Java

Overclockers is supported by our readers. When you click a link to make a purchase, we may earn a commission. Learn More.

RedDragonXXX

Senior RAM Pornographer
Joined
Mar 3, 2005
Location
Jacksonville, FL
Hey guys I'm working on a Java project and I got pretty much everything done but the search part. We're supposed to search array of objects and I'm little confused with what to pass as parameters for my search method.

Basically I have two arrays:

One array has all the data as array of objects.
Second array serves as search key which is also array of objects.

Here is the code (keep in mind this is just to test the first index in the array for the time being until I can get the code working)


Method:
Code:
public void sequentialSearch(SearchCountry[] searchData)
 {
     searchData = searchList;
     if (countryList[1].getCountryName().equals(searchData[1].getSearchName()))
        System.out.println("Country Found");
     else
       System.out.println("Country Not Found");
             
 }

And the part that gets me confused is that I can't pass it in the main without syntax error:

Code:
countryList.sequentialSearch(searchList);

If anyone has any idea of what I'm doing wrong please let me know.
 
Your method is receiving a parameter searchData, and the first thing you do is replace the parameters value with the value of searchList...

It does not matter what the variable name is in the main method (used to call the search method), the search method will only see the name specified in the method call definition.
 
Your method is receiving a parameter searchData, and the first thing you do is replace the parameters value with the value of searchList...

It does not matter what the variable name is in the main method (used to call the search method), the search method will only see the name specified in the method call definition.


Code:
 public void sequentialSearch(SearchCountry[] searchData)
 {
     
     if (countryList[1].getCountryName().equals(searchData[1].getSearchName()))
        System.out.println("Country Found");
     else
       System.out.println("Country Not Found");
             
 }

This still doesn't work. I don't get how I can call it in main without getting syntax error.
 
What's teh actual error message?

Is countryList a global variable (defined outside the main method)? If not, you need to also include it as a parameter:

public void sequentialSearch(SearchCountry[] searchData, something[] countryList)

Also remember arrays start from[0], not [1], so you could get an ArrayIndexOutOfBounds if you did not actually have two entries in that array...

Also you are only searching one cell of the array, not looping through it.

Do you get the error while compiling or while running the program?

edit: if you don't mind printing more of the program it could be easier to debug
 
Here is the screenshot of the actual error:

rdA8g.png

countryList is an array of object that I have created from another class (ECountry) and contains a list of countries (45 countries).

searchList is an array of objects that I have created from another class (SearchCountry) that contains countries that I will be searching for. It only contains country names.

For now I'm just trying to get the method to work that's why I'm only searching one cell. Cell number doesn't matter at this point if the method doesn't work. If I can get it working I can create a loop later that will go through entire array.

At this point I would just like to see if I can get the method working so that it can look at index 1 of countryList, see if it equals index 1 of searchList and print out appropriate message. But I can't figure out the parameter part.
 
Here is the screenshot of the actual error:

rdA8g.png

countryList is an array of object that I have created from another class (ECountry) and contains a list of countries (45 countries).

So somewhere you have defined something like:

Code:
ECountry[] countryList = new ECountry[size]

searchList is an array of objects that I have created from another class (SearchCountry) that contains countries that I will be searching for. It only contains country names.

And something like this:

Code:
SearchCountry[] searchList = new SearchCountry[size]

And added values to both arrays?

For now I'm just trying to get the method to work that's why I'm only searching one cell. Cell number doesn't matter at this point if the method doesn't work. If I can get it working I can create a loop later that will go through entire array.

Ok, no problem

At this point I would just like to see if I can get the method working so that it can look at index 1 of countryList, see if it equals index 1 of searchList and print out appropriate message. But I can't figure out the parameter part.

I'm trying to figure out if this is a school assignment or just something for fun? I'm happy to help you figure it out, but if it's a school assignment you need to do most of the figuring out. :D

I think the way you are trying to run the search is wrong. If you where calling it like you mention:

Code:
countryList.sequentialSearch(whatever)

Then countryList should be some class implementing a sequentialSearch method. However you mentioned it's an Array meaning it only implements the predefined functions like getting the size of it etc.

Instead you should be calling the method directly:

Code:
sequentialSearch(searchList);

Now if the sequentialSearch was a method of the eCountry class then referring to your earlier code you would do:

Code:
countryList[1].sequentialSearch(whatever)

That way you would be referring to the actual ECountry object, not the Array
 
Reading your first question again, I'm getting a feeling that it's an assignment?

You say you need to search an array, but is there a reason you also want the search terms to also be in an array?
 
Yes both arrays have values added to them from the text file. That part I got. ECountry has all the countries, while SearchCountry has only the countries I'm searching for.

I have tried everything I can think of so far and can't figure out. This is a school assignment and its not really something we have covered in class. We have seen examples of how to search for array of integers (that part I got and its simple), but this is totally different and I'm starting to think its not possible (having one array of objects search through another array of objects).

IDK, I feel like I have hit the wall and don't know where to go from here.
 
Ok.

Let's say you have a main class which loads all the data etc. You have two alternatives. Since you are already managing to load the data to the arrays I'm just assuming you have loadCountries and loadSearchTerms methods which populate them:

Code:
public class Example {
	public static void main(String[] args) {

		// ignore this since you already have the data in the arrays
		Ecountry[] countryList = loadCountries();
		SearchCountry[] searchList = loadSearchTerms();

		sequentialSearch(countryList, searchList);

		public void sequentialSearch(Ecountry[] countryList, SearchCountry[] searchList) {
			// do your search
		}
	}
}

public class Example {

	private Ecountry[] countryList;
	private SearchCountry[] searchList;

	public static void main(String[] args) {

		// ignore this since you already have the data in the arrays
		countryList = loadCountries();
		searchList = loadSearchTerms();

		sequentialSearch();

		public void sequentialSearch() {
			// do your search
		}
	}
}

You'll see the main difference here is that in the latter the arrays are global variables, thus the method can access them directly. In the first one they are introduced in the main method which limits their visibility to other methods (so you need to give them as parameters).

Which one you pick is a matter of taste, and also depends on how the arrays will be accessed from elsewhere. For example if you need access from a lot of different methods it could be logical to define it as a global variable. If you will only access it from one method then you might pass it as a parameter in the method call etc.

Does this help?
 
Ok, now that you showed more code I understand it better.

Hey guys I'm working on a Java project and I got pretty much everything done but the search part. We're supposed to search array of objects and I'm little confused with what to pass as parameters for my search method.

Basically I have two arrays:

One array has all the data as array of objects.
Second array serves as search key which is also array of objects.

Here is the code (keep in mind this is just to test the first index in the array for the time being until I can get the code working)

In this class both countryList and searchList where global variables, so the sequentialSearch can access them directly, meaning you can remove the parameter completely:

Method:
Code:
public void sequentialSearch(SearchCountry[] searchData)
 {

You don't need to do any assignments since both arrays already have the data loaded:

Code:
     searchData = searchList;
     if

Here searchData should just be searchList
Code:
(countryList[1].getCountryName().equals(searchData[1].getSearchName()))
        System.out.println("Country Found");
     else
       System.out.println("Country Not Found");
             
 }
And the part that gets me confused is that I can't pass it in the main without syntax error:

Code:
countryList.sequentialSearch(searchList);

If anyone has any idea of what I'm doing wrong please let me know.

And here you should be calling country.sequentialSearch() since this is where the method is (assuming you declared it like this):

Code:
Country country = new Country(some int value);
 
I did what you suggested but now I'm getting NullPointerException error. I've made a new object country. As such Country country = new Country();
I removed parameter from my constructor since it only specified size of the array and I hard coded it in. I called it using:

country.sequentialSearch();

Compiles but comes with NullPointerException error.

Only way it works is if I call search using either countryList or searchList array. If for example I use:

countryList.sequentialSearch();

It will only return results if I only use countryList[index].getCountryName in search method. If I use searchList[index].getSearchName in the search method it will return NullPointerException error. It also returns the same error if I try to use both arrays in the method.
 
I'd probably skip on arrays alltogether and use ArrayLists instead. Here's an example, which might work:
Code:
import java.util.ArrayList; 

public ArrayList<Country> sequentialSearch(ArrayList<Country> needle, ArrayList<Country> haystack)
{
    ArrayList<Country> matches = new ArrayList<Country>();
    for( int i=0; i<needle.length; ++i)
    {
        Country test = needle.get(i);
        if( -1 != haystack.indexOf(test) )
            matches.add(test);
    }
    
    return matches;
}
 
It's true that an ArrayList would be a lot easier and elegant, but if the teacher specifically requested using an Array I'm sure he would not appreciate cutting corners...

If you get a nullpointer when using searchList[index].getSearchName it means that there is no data in that cell. If you use an IDE which allows using break points and viewing variable contents while in debug mode you could see what's in the array.

Otherwise you could make a method for debugging, something like this:

Code:
printECountries() {
	for (i=0; i<countryList.length; ++i) {
		if (countryList[i] != null) {
			System.out.println("Ecountry with index " + i " has country " + countryList[i].getCountryName());
		} else {
			System.out.println("Ecountry with index " + i " is null");
		}
	}
}

In your Country class will print out the contents of the array. You can adapt the same for the searchList.

Then before using your search method you can debug by calling those methods to verify that you you have all the data you expect loaded into the arrays...

edit: alternatively you could add some logging into the readIn and readSearchFile classes, something like:
Code:
System.out.println("Added entry " + countryNumber " to countryList with value: " + countryList[countryNumber].getCountryName());

After you have assigned the data. Again the same could be done to the searchList.
 
Last edited:
Yea we were instructed only to use arrays.

Drop I sent you a message with some code. Since the debug method only works if I call it with an array of object and not the new object I created like so:

If I call in the main;

Code:
countryList.printECountries();

It will print out the countries.

If I try with new created object;

Code:
Country country = new Country();
Code:
country.printECountries();

It will print null for all indexes.

How can I make so that the new object I create can see what inside both of my array of objects that were created from two different classes?
 
The reason the latter prints null is that you probably did not load data into it.

The constructor in your Country class only initiates the arrays, so when you do:

Code:
// initiates the arrays with null values
Country country = new Country();

There is still no data. First you need to call the readIn method to read the data into the variable...

If you'd be ready to change the architecture a bit you could make it more logical though. :)
 
I've finally figured out how to do this and its working great now.

Big thanks to dropadrop :thup: and everyone else that contributed.
 
Back