-2

I have 2 lists in my program; one of the list already has data. I need to create a new List and pass few data from previous list.

Following is the code I use :

List<Class1> result = function();
List<Class2> newList = new ArrayList<Class2>();

for(int i=0; i < result.size(); i++) {
     newList.get(i).setValue(result.get(i).getValue());
     //setValue() is setter function in Class2
     //getValue() is getter function in Class1
    }
  return newList;

I get an error in this particular line when I try to run the code:

newList.get(i).setValue(result.get(i).getValue());

The error is :

java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
java.util.ArrayList.rangeCheck(ArrayList.java:635)
java.util.ArrayList.get(ArrayList.java:411)

How do I resolve this issue ? Need some help with it.

Arnab
  • 63
  • 3
  • 14
  • 5
    You just created an empty `newList`, with no `Class2` objects in it. What do you expect `newList.get(0)` to return exactly? – azurefrog Nov 20 '15 at 22:36

1 Answers1

1

Let's say you have a variable called obj1 and obj2. obj1 is an instance of some object. obj2 is null. Then you set obj2's variable to obj1 variable. What do you get? NullPointerException because obj2 is null.

To solve this problem you must create an object. For example in the for loop (before your newList.get(...) method). You want to either copy the object or copy some variables. To do this do something like this in the for loop.

newList.set( i, result.get(i) ); // if you want to copy the class

newList.set( i, new Class2(/* ... */) );
newList.get(i).setValue( result.get(i).getValue() ); // to copy variable

@Edit you can use 1st method (newList... = result...) only if Class2 extends Class1

Mibac
  • 8,990
  • 5
  • 33
  • 57
  • For my case, the second method is applicable. But, I don't think that newList.get(i) = new Class2(/* ... */) is going to work. can you please suggest some way, so that I can copy a class member from 1 list to the other ? @mibac – Arnab Nov 20 '15 at 22:56
  • @Arnab why do you think so? in place of `/* ... */` you just put constructor parameters. – Mibac Nov 20 '15 at 22:57
  • I did try it with the constructor params. The error which it generate is for "newList.get(i)", and the error is "The left-hand side of an assignment must be a variable". – Arnab Nov 20 '15 at 23:02
  • Thanks for the modified one. But, with the new code, I now get an "IndexOutOfBoundsException: Index: 0, Size: 0" error. Any idea, why is this happening ? @mibac – Arnab Nov 20 '15 at 23:24
  • any other suggestions on this issue ?? – Arnab Nov 23 '15 at 20:38