0

I'm trying to access an element inside an array, which is inside an ArrayList. For example, lets say:

ArrayList list = new ArrayList();

int[] x = new int[2];
x[0] = 2;
x[1] = 3;

list.add(x);

So, later on lets say i'd like to print x[1], I've tried doing this:

System.out.println(list.get(0)[1]); 

But this gives me: Solution.java:47: error: incompatible types: Object cannot be converted to int[]

I tried to store the array in another array and access the new array but this gives the same error message.

I'm relatively new to java and moving from JavaScript where variables aren't nearly strict. I'm not extremely familiar with collections, I found this answer here:

Array inside arraylist access

But as you can see, this solution is not working for me. If there is anything i'm neglecting or overlooking - I would greatly appreciate any advice. Thank you.

EDIT: This question isn't weather or not I should use raw data types - though I will make sure to review this more in the future - raw data types are being used and the question is how to access them.

Jonathan Hinds
  • 305
  • 2
  • 13

2 Answers2

2

You need to declare your ArrayList's type which in this case is int[]. If you don't do this, this ArrayList will assume that it holds Objects, hence the error you're getting. It would look something like this:

ArrayList<int[]> list = new ArrayList<int[]>();

Brian
  • 823
  • 6
  • 14
  • this is perfect, thank you so much! I need to become more familiar with generics and type declaration. I also appreciate the quick response and understanding the question. I will make sure to review what was posted by GBlodgett, though I assure you my question is different. – Jonathan Hinds Oct 13 '18 at 00:43
  • For the record, it's quicker to type `List list = new ArrayList<>();` or `var list = new ArrayList();` in Java 10. – Jacob G. Oct 13 '18 at 00:44
1

The get() method for ArrayList just requires the index. So, simply use:

System.out.println(list.get(0));
System.out.println(list.get(1));

etc. Hope this helps.

  /**
 * Returns the element at the specified position in this list.
 *
 * @param  index index of the element to return
 * @return the element at the specified position in this list
 * @throws IndexOutOfBoundsException {@inheritDoc}
 */
public E get(int index) {
    rangeCheck(index);

    return elementData(index);
}
C0D3JUNKIE
  • 596
  • 1
  • 6
  • 16
  • This returns the array, but not an index of the array. The goal was to access a specific index of the array. I appreciate the response though. – Jonathan Hinds Oct 13 '18 at 00:50
  • Also, I tried storing the array in another array and then accessing that one. so, int[] f = list.get(0), this was also throwing the same error. – Jonathan Hinds Oct 13 '18 at 00:51
  • 1
    Right, I saw the other answer went back and looked at the question again, and saw my error. Glad you got what you needed. – C0D3JUNKIE Oct 13 '18 at 01:02