Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Can't get array-backed List to "write through" back to the array

 
Joe Kaz
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Greetings,
I can't seem to get updates to an array-backed List, created with asList(), to write back to the originating array.
The Arrays class asList() API says: "Changes to the returned List "write through" to the array."
This code seems to demonstrate that the array is not being updated. Can anyone tell me what I'm doing wrong?
Thanks much
Joe Kaz
import java.lang.reflect.Array;
import java.util.*;
public class TestArray {
public static void main(String args[]) {
String[ ] array = {"You", "Me", "Her", "Him"};
ArrayList ourList;
ourList = new ArrayList (Arrays.asList(array) );
System.out.println("List length: " + ourList.size());
System.out.println("List contains: " + ourList);
System.out.println("Array length: " + array.length);
for (int i =0; i<Array.getLength(array); i++) System.out.println("Array is: " + Array.get(array, i));
System.out.println(" ");
ourList.set( 1, "XXXXX"); // change AN OBJECT in THE LIST
ourList.add("YYYYY"); // ADD AN OBJECT TO THE LIST
System.out.println("List length now: " + ourList.size());
System.out.println("List now contains: " + ourList);
System.out.println("Array length now: " + array.length);
for (int i =0; i<Array.getLength(array); i++) System.out.println("Array is now: " + Array.get(array, i));
} }
 
Jon Strayer
Ranch Hand
Posts: 133
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Joe Kaz:
Greetings,
I can't seem to get updates to an array-backed List, created with asList(), to write back to the originating array.
The Arrays class asList() API says: "Changes to the returned List "write through" to the array."

True, but the constructor for ArrayList copies the data from the passed in collection.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic