0

I have a List with Object[] inside and I want to access a value of one of the Objects[]. This is how my code looks:

private List<Object> trackList;
trackList = new ArrayList<>();

Integer random = (int)(Math.random() * ((100 - 0) + 1)) + 0;
Integer random2 = (int)(Math.random() * ((100 - 0) + 1)) + 0;
Object[] currTrack = new Object[]{random1, random2};
trackList.add(currTrack);

Integer value1 = trackList.get(0)[1];

Getting: "Array type expected; found:'java.lang.object'

I think I am missing something very simple. Help would be great, thanks.

3
  • 2
    Why not declare trackList as List<int[]> and currTrack as int[]? Commented Jul 17, 2019 at 3:06
  • 1. You need to type cast. from Object to Integer. Commented Jul 17, 2019 at 3:09
  • "I have a List with Object[] inside" -> clearly not ... your list does not contain Object[] or at least it's not type as a list of arrays ... and not using typed arrays and lists, like int[] and List[int[]] is weird in my opinion. Commented Jul 17, 2019 at 3:10

2 Answers 2

5

You declared your list like this:

List<Object> trackList;

So when you do:

trackList.get(0)

That gets you an Object and not an Object[].

You need to cast it:

((Object[])trackList.get(0))[1]

But then you have another problem, cause that expression above returns you an Object and you want to assign it to an Integer.

So you need another cast.. complete line should be:

Integer value1 = (Integer)((Object[])trackList.get(0))[1];

By the way, it'd be easier to just declare the list to contain what you'll be actually putting into it.

Sign up to request clarification or add additional context in comments.

1 Comment

As I assumed an simple solution for that mistake. List<Object[]> trackList; works perfectly. Thanks for your help :)
0

In you list declaration you set that list is contains of Objects not Object[]:

List<Object> trackList;

So when you do:

trackList.get(0) That gets you an Object and not an Object[]

You need to change List initialization to

List<Object[]> trackList;

1 Comment

List<Object[]> trackList; works perfectly and was what I was looking for. Thanks...drove me crazy

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.