Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 15 of 15

Thread: How to use this 2d ArrayList class?

  1. #1
    Junior Member
    Join Date
    Jan 2011
    Posts
    15
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Talking How to use this 2d ArrayList class?

    Hello,

    I am new to java, these forums and know very little about object orientated programming.
    I am trying to convert a C++ program to java which uses 2 dimentional vectors.
    Searching google I found this class but I have no idea how to use it and build it into my program.

    Any help would be much appreciated.


  2. #2
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: How to use this 2d ArrayList class?

    In Java, you can fake 2D ArrayLists by making an ArrayList of ArrayLists of some type (it's not as confusing at it sounds).

    I wrote that class as an example of how to utilize this, but it's really not necessary to use that class at all. You can use this idea the same way vector<vector<type>> is used.

    For example, say your C++ code looked something like this:
    // really C++ code
    // I know that by using references/pointers this could be more efficient, but that's beyond the scope of this example
    vector<vector<int>> v;
    v.push_back(vector<int>());
    v.push_back(vector<int>());
    v.push_back(vector<int>());
    v[0].push_back(1);
    v[0].push_back(2);
    v[1].push_back(3);
    v[1].push_back(4);
    v[1].push_back(0);
    v[2].push_back(5);
    // now have the following contents:
    // row 0: 1, 2
    // row 1: 3, 4, 0
    // row 2: 5
    // get the element at row 1 and column 2
    int number = v[1][2];

    The Java-equivalent code would be (it's very similar to the above code, though there are a few differences):
    // Create an ArrayList of ArrayLists of Integers
    ArrayList<ArrayList<Integer>> my2DArrayList = new ArrayList<ArrayList<Integer>>();
    // add in a few ArrayLists. These contain the "rows" of the 2D ArrayList
    my2DArrayList.add(new ArrayList<Integer>());
    my2DArrayList.add(new ArrayList<Integer>());
    my2DArrayList.add(new ArrayList<Integer>());
    // you can retrieve rows using get(), then treat that 1D arrayList as the column.
    my2DArrayList.get(0).add(1);
    my2DArrayList.get(0).add(2);
    my2DArrayList.get(1).add(3);
    my2DArrayList.get(1).add(4);
    my2DArrayList.get(1).add(0);
    my2DArrayList.get(2).add(5);
    // my2DArrayList now contains this:
    // row 0: 1, 2
    // row 1: 3, 4, 0
    // row 2: 5
    // to retrieve a specific element, you need to first get the ArrayList of the row you want, then retrieve the column from that arraylist you want
    // get element at row 1 and column 2
    int number = my2DArrayList.get(1).get(2);

    If you do want to use my "wrapper class", you're more than welcome to. I fixed it recently (at the time I posted this, actually) because I actually never really tested it in the past (how embarrassing). It basically embodies this idea into short and concise methods of how you would perform common operations such as getting an element at a specific row and column.
    Last edited by helloworld922; January 10th, 2011 at 09:32 PM.

  3. #3
    Junior Member
    Join Date
    Jan 2011
    Posts
    15
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: How to use this 2d ArrayList class?

    Thank you. This is what I needed.

    ... one last thing, how would I go about reassigning a new value to an existing element?
    Last edited by J05HYYY; January 11th, 2011 at 05:52 PM.

  4. #4
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: How to use this 2d ArrayList class?

    myArrayList2D.get(row).set(col, value);

  5. #5
    Junior Member
    Join Date
    Jan 2011
    Posts
    15
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: How to use this 2d ArrayList class?

    Cheers - answered my questions exactly.

  6. #6
    Junior Member
    Join Date
    Jan 2011
    Posts
    15
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: How to use this 2d ArrayList class?

    One more last thing ... how do I copy an ArrayList? I tried this:

    vlinefreq = vfrequency.get(s);

    but it doesn't seem to work as I imagined it to.

  7. #7
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: How to use this 2d ArrayList class?

    Do you mean a deep copy? Java works via references so it's a rather big pain to perform a deep copy.

    Your code simply gets a reference to the ArrayList at row s. You can copy that ArrayList, but any changes you make to objects inside that ArrayList will effect those inside vfrequency.

    vlinefreq = vfrequency.get(s).clone(); // creates a shallow copy of row s

    If you need a deep copy, you could go through and call clone on every element inside of vlinefreq. However, this is not guaranteed to work or give you a deep copy since implementation of Clonable is rather sporadic.

  8. #8
    Junior Member
    Join Date
    Jan 2011
    Posts
    15
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: How to use this 2d ArrayList class?

    Yeah, in that case I need a deep copy.

    Meh, no need to use clone but still a pain to cycle through every element.

    vlinefreq.clear();
    int x;
    for (x=0; x < vfrequency.get(s).size(); x++)
    {
    	vlinefreq.add(vfrequency.get(s).get(x));
    }
    Last edited by J05HYYY; January 18th, 2011 at 08:18 PM.

  9. #9
    Junior Member
    Join Date
    Jan 2011
    Posts
    15
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: How to use this 2d ArrayList class?

    Interesting. Maybe the code I just gave didn't work. I have just tried something only slightly more complex and it didn't work:

    ArrayList<Integer> vtemplinenum = new ArrayList<Integer>();
    ArrayList<ArrayList<Integer>> vlinenum = new ArrayList<ArrayList<Integer>>();
     
    vtemplinenum.add(1);
    vtemplinenum.add(2);
    vtemplinenum.add(3);
     
    vlinenum.add(vtemplinenum);
     
    vtemplinenum.clear();
     
    System.out.println(vlinenum.size());
    System.out.println(vlinenum.get(0).size());

    The out put is 1 & 0 but if I get rid of "vtemplinenum.clear();", it's 1 & 3 ... More testing needed.

  10. #10
    Junior Member
    Join Date
    Jan 2011
    Posts
    15
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: How to use this 2d ArrayList class?

    Okay, I have tested the code I gave earlier and found that it works ie. it doesn't change the original ArrayList.

    ArrayList<Integer> vlinefreq = new ArrayList<Integer>();
    ArrayList<Integer> vfrequency = new ArrayList<Integer>();
     
    vlinefreq.add(1);
    vlinefreq.add(2);
    vlinefreq.add(3);
     
    vfrequency.clear();
    int x;
    for (x=0; x < vlinefreq.size(); x++)
    {
    	vfrequency.add(vlinefreq.get(x));
    }
     
    System.out.println("OldLineFreq = " + vlinefreq);
    System.out.println("OldFrequency= " + vfrequency);
     
    vlinefreq.set(0,5);
     
    System.out.println("NewLineFreq = " + vlinefreq);
    System.out.println("NewFrequency =" + vfrequency);

    Output:
    OldLineFreq = [1, 2, 3]
    OldFrequency= [1, 2, 3]
    NewLineFreq = [5, 2, 3]
    NewFrequency =[1, 2, 3]

    ... what is strange is that it doesn't work the same when adding an entire ArrayList, like I mentioned in my last post.

  11. #11
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: How to use this 2d ArrayList class?

    Wait, wait, wait.

    Are you trying to create an independent copy of an ArrayList? That is very simple, just use the ArrayList(Collection<? extends E> c) constructor.

    Here is some sample code that shows its implementation:
    import java.util.ArrayList;
     
    public class MainClassTest 
    {
        public static void main(String args[]) 
        {
        	ArrayList<String> values = new ArrayList<String>();
        	values.add("Test");
        	values.add("Test1");
        	values.add("Test2");
        	values.add("Test3");
        	values.add("Test4");
        	ArrayList<String> valuesDuo = new ArrayList<String>(values);
        	valuesDuo.add("Test5");
        	valuesDuo.set(2,"Test200");
     
        	System.out.println(values);
        	System.out.println(valuesDuo);
        }
    }
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  12. #12
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: How to use this 2d ArrayList class?

    That still produces a soft copy. Java makes it rather cumbersome to get a good deep copy because it functions using references/pointers for objects. Even Cloneable objects sometimes return only shallow copy. If you're using your own classes, you can implement Clonable to provide a true deep copy. However, if you're mixing in other API's (including the standard API) you're going to have a lot of custom code just to provide a deep copy.

    // knowing that we have Points which take int x and int y, we can clone them manually.
    Point p1 = new Point(1,2);
    // a manual clone of p1. It's guaranteed to be a deep-copy
    Point p2 = new Point(p1.x, p1.y);

  13. #13
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: How to use this 2d ArrayList class?

    But doesn't a soft copy keep the references? The constructor I used above allows you to edit values of one array without changing the values of the other array. Wouldn't that mean it isn't a soft copy? Maybe I missed something.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  14. #14
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,318
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: How to use this 2d ArrayList class?

    Quote Originally Posted by aussiemcgr
    The constructor I used above allows you to edit values of one array without changing the values of the other array. Wouldn't that mean it isn't a soft copy?
    The changes made in the code you posted changes the references, so all it is doing is reassigning the references to something else - this is only reflected in the List where the change occurred (all other references still refer to the previous object). In more complex scenarios, change the variables of an object within the array and the effect will be reflected in every reference. Here's a modification of the code you posted to demonstrate, printing the arrays will show that the values of both arrays are identical
    public class Test {
     
    	String string;
    	public Test(String s){
    		string = s;
    	}
     
    	public static void main(String args[])
        {
            ArrayList<Test> values = new ArrayList<Test>();
            values.add(new Test("Test"));
            values.add(new Test("Test1"));
            values.add(new Test("Test2"));
            values.add(new Test("Test3"));
            values.add(new Test("Test4"));
            ArrayList<Test> valuesDuo = new ArrayList<Test>(values);
            valuesDuo.get(2).string = "Test200";
     
     
            System.out.println(values);
            System.out.println(valuesDuo);
        }
    	@Override
    	public String toString(){
    		return string;
    	}
    }
    Last edited by copeg; January 19th, 2011 at 01:45 PM.

  15. #15
    Junior Member
    Join Date
    Jan 2011
    Posts
    15
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: How to use this 2d ArrayList class?

    No, you didn't miss something...

    ArrayList<String> valuesDuo = new ArrayList<String>(values);

    Means, I think that it creates a new instance so it doesn't change the original. Anywhoo I tested it just to make sure it works:

    import java.util.ArrayList;
     
    class mainprogram
    {  
            public static void main(String args[])
            {
    		ArrayList<Integer> vlinefreq = new ArrayList<Integer>();
    		ArrayList<Integer> vfrequency = new ArrayList<Integer>();
     
    		vlinefreq.add(1);
    		vlinefreq.add(2);
    		vlinefreq.add(3);
     
    		vfrequency = new ArrayList<Integer>(vlinefreq);
     
    		System.out.println("OldLineFreq = " + vlinefreq);
    		System.out.println("OldFrequency= " + vfrequency);
     
    		vlinefreq.set(0,5);
     
    		System.out.println("NewLineFreq = " + vlinefreq);
    		System.out.println("NewFrequency =" + vfrequency);
            }
    }

    Output:
    OldLineFreq = [1, 2, 3]
    OldFrequency= [1, 2, 3]
    NewLineFreq = [5, 2, 3]
    NewFrequency =[1, 2, 3]

    ... good stuff, cheers to both of you

Similar Threads

  1. How to use an ArrayList and what is its advantage over array?
    By JavaPF in forum Java SE API Tutorials
    Replies: 4
    Last Post: December 21st, 2011, 04:44 AM
  2. Ordering ArrayList by 3 conditions as you add to ArrayList
    By aussiemcgr in forum Collections and Generics
    Replies: 4
    Last Post: July 13th, 2010, 02:08 PM
  3. [SOLVED] Passing arrayList inside class
    By KrisTheSavage in forum Collections and Generics
    Replies: 1
    Last Post: March 27th, 2010, 12:45 PM
  4. Arraylist or Arraylist Object?
    By igniteflow in forum Collections and Generics
    Replies: 2
    Last Post: September 11th, 2009, 02:08 AM
  5. [SOLVED] Extracting an How to ArrayList from an ArrayList and convert to int??
    By igniteflow in forum Collections and Generics
    Replies: 2
    Last Post: August 16th, 2009, 01:11 PM