user4811490
user4811490

Reputation:

How to compare an object containing a string?

I have an array that contains the following strings

Object[] array = {"Tom","Jim","George"};

How can I compare each object as a String?

* Array must be type of Object and contain only String type of objects for my problem.Using String[] is pretty much obvious enough.

Upvotes: 0

Views: 60

Answers (2)

Frank Puffer
Frank Puffer

Reputation: 8215

Like that:

String testString = "xyz";
int result = testString.compareTo((String)array[i]);

or for example:

int result = ((String)array[j]).compareTo((String)array[i]);

If you are not really sure if the array element is a String, use the instanceof operator to check.

Upvotes: 1

Krismorte
Krismorte

Reputation: 632

Try this

int result=-1;
    Object parameter="Tom";
    for(Object o: array){
    if(o.toString().equals(parameter.toString())){
     result=1;
    }
    }

Upvotes: 0

Related Questions