NBC
NBC

Reputation: 1698

How to return an array from a list [Java]

Here is how my code is set up:

public String[] function(List<String[]> playerList){
i = 5
return playerList[i];

When I try to run this code, I get the error:

Array type expected; found: 'java.util.List<java.lang.String[]>'

I know I'm screwing something up by mixing my arrays and lists, what would be the right way of fixing this code, assuming I can't change my list input to an array?

Upvotes: 3

Views: 2353

Answers (4)

bipartite
bipartite

Reputation: 101

So, you were trying to get an array of strings however, there could be two (2) things you wanted to take a look. First, you might want to specify playerList as an ArrayList<String> and then(second), you are trying to return playerList[i] as string and not as an array of string as specified String[].

public String[] function(List<String[]> playerList){
  i = 5
  return playerList[i];

You might want to try this instead?

return playerList.toArray(new String[playerList.size()]);

Upvotes: 0

kerato2323
kerato2323

Reputation: 125

playerList is List type, for accessing element in the List you must call get function.
for example >> playerList.get(0) , then you will get element's value in index-0. In this case, you will return String of Array. And if you want accessing that Array element, you can use playerList.get(0)[i]

Upvotes: 0

lovespring
lovespring

Reputation: 440

not like c++, which can do operator overloading.

in java, playerList is a list, you cannot apply "[]" to it, but the list's element/item is an Array type (String[]). so, you should use list.get() and with it's element, you could use [] operator: (playerList.get(i))[0]

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201487

You access an element at an index in a List with a call to List.get(int index) (not [], that is accessing an element in an array). Like,

return playerList.get(i);

Upvotes: 5

Related Questions