standshik said:
okay i'm new to java. i need to read some stuff from a file and store
into some data structure.
say i have the following in a file
A B C
D E
F G H I
no i need to store such a way so that i can access (i,j)th element at
anypoint of time.
i can do that very easily in C++ using vector of vectors of string.
how do i do that in java? i tried using arraylist of arraylists but
could not get it right?
Can you somebody please explain in details how can i do that? possibly
with a small fragmant of code?
thanks
kaushik
This should do all you ask for:
import java.util.ArrayList;
import java.util.Iterator;
public class array
{
static public void main(String[] args)
{
ArrayList parent = new ArrayList();
{
ArrayList child = new ArrayList();
child.add( "A" );
child.add( "B" );
child.add( "C" );
parent.add( child );
}
{
ArrayList child = new ArrayList();
child.add( "D" );
child.add( "E" );
parent.add( child );
}
{
ArrayList child = new ArrayList();
child.add( "F" );
child.add( "G" );
child.add( "H" );
child.add( "I" );
parent.add( child );
}
/*
* Following prints "parent has 3 elements" which is what we
* expect
*/
System.out.println("parent has " +parent.size()+ " elements." );
/*
* The following loop prints:
* A B C
* D E
* F G H I
*/
for (Iterator parentIterator = parent.iterator() ;
parentIterator.hasNext() ;
) {
ArrayList child = (ArrayList)parentIterator.next();
for (Iterator childIterator = child.iterator() ;
childIterator.hasNext() ;
) {
String str = (String)childIterator.next();
System.out.print(str + " " );
}
System.out.println();
}
System.out.println();
/*
* Accessing individual elements of the array -- Need the ugly
* typecasts (with Java 1.4)
*/
System.out.println("Element ( 1, 1 ) is: " +
((ArrayList)parent.get(1)).get(1));
System.out.println("Element ( 0, 2 ) is: " +
((ArrayList)parent.get(0)).get(2));
System.out.println("Element ( 2, 2 ) is: " +
((ArrayList)parent.get(2)).get(2));
System.out.println();
/*
* Access an element outside the range, and you get an
* java.lang.IndexOutOfBoundsException
*/
System.out.println("Element ( 1, 3 ) is: " +
((ArrayList)parent.get(1)).get(3));
}
}