user2797374
user2797374

Reputation: 23

JAVA accessing items inside an object array

so I have got a class that has the following method signature

public void doStuff(**Object[] lists**)
{ 
    ...
}

I am having trouble figuring out how to access the individual elements in the lists

For example, if one of the objects passed (say list[0]) is a Character array (Character[] = {'a', 'd', 'z'}) then how would I find out from this method that lists[0] has 'a' 'd' and 'z' in it?

I have tried code like: Object list0 = list[0]; but then I am absolutely lost on how to get the contents of list[0] (in this case, 'a' 'd' and 'z').

Any ideas?

(UPDATE)

Thanks for the responses. I was able to modify your guys' ideas and make it work :)

Upvotes: 2

Views: 800

Answers (2)

dognose
dognose

Reputation: 20909

Just drill down the param as required:

public void doStuff(Object[] lists) 
{ 
   Object entry0 = lists[0]; //Object Array only contains objects.
   char[] charArr = (char[]) entry0; // Explicit cast: You know that lists[0] is a char Array!
   for (char c : charArr)
   {
     System.out.println("Char Array contains: " + c);
   }
}

Upvotes: 4

William Falcon
William Falcon

Reputation: 9823

If your arrays have strings: (otherwise replace whatever object you are using)

Object first = lists[0];
ArrayList<String> individual = (ArrayList<String>)first;
String itemOne = individual.get(0);

Upvotes: 1

Related Questions