Jump to content

How to copy arrays in Java?

- - - - -

  • Please log in to reply
7 replies to this topic

#1
AnnexTrunks

AnnexTrunks

    Newbie

  • Members
  • Pip
  • 5 posts
I am working with arrays and I am trying to figure out how to copy an array, using this website as help.http://download.orac...yOf(int[], int)

I will paste my code below, but what I have so far is an array declared, named it "book", did some loops to get some user input and then display the outcome, and that works fine. I was told when you are copying an array, you create a new object and that's where I am stuck. I don't understand how to create and initialize this new object in order to copy my array. I hope I have the right idea at least lol.

I have a portion of it commented out while I was working with this.


import java.util.ArrayList;

import javax.swing.JOptionPane;

/* Exam Practice # 2

 * 10.20.2011

 * This file loads the array list with PhoneBookEntry objects, and displays the

 * content.

 */

public class PhoneBookDemo

{


    public static void main(String[] args)

    {   String name;

        String phoneNumber;

        String input;

        int inData;

        //Creates an array list that holds phonebookentrys, the name of it is called book

        ArrayList < PhoneBookEntry > book = new ArrayList < PhoneBookEntry > ();

        

        //bookPhone is my second object 

        PhoneBookEntry bookPhone;

        do//assure input is greater than 0

            {

            input = JOptionPane.showInputDialog("How many phone book listings to enter");

            inData = Integer.parseInt(input);

            }

        while(inData < 1);

        //load the array list

        for (int i = 0; i < inData; i++)

            {

            name = JOptionPane.showInputDialog(null,

            "Enter the name:", "Entry" + (i + 1) +

            JOptionPane.PLAIN_MESSAGE);

            

            phoneNumber = JOptionPane.showInputDialog(null,

            "Enter the phone number:", "Entry" + (i + 1) +

            JOptionPane.PLAIN_MESSAGE);

            

            //Primary phonebook object (named it book)

            book.add(new PhoneBookEntry(name, phoneNumber));

            

            }

       //Create a loop that gets objects from the other class file and maybe switch them around

       System.out.println("Name"  + "\tPhone Number" );

       for (int i = 0; i < book.size(); i++)

            {


             System.out.println(book.get(i).getName() + "\t" + book.get(i).getPhoneNumber());

            }

      

       

            //Secondary phonebook object for switching

            //Use methods from the Array list to switch, or replace

            //Print out a paper for each one so you know they all work

            //Refer to Page 433 for "Copying Arrays"

            //http://download.oracle.com/javase/6/docs/api/java/util/ArrayList.html

            //http://download.oracle.com/javase/6/docs/api/java/util/Arrays.html

              bookPhone.add(new PhoneBookEntry(name, phoneNumber));

            

            

       

//**********************Secondary phonebook object****************************\\ 

       

        //PhoneBookEntry bookPhone;

        /*do//assure input is greater than 0

            {

            input = JOptionPane.showInputDialog("How many phone book listings to enter");

            inData = Integer.parseInt(input);

            }

        while(inData < 1);

        //load the array list

        for (int i = 0; i < inData; i++)

            {

            name = JOptionPane.showInputDialog(null,

            "Enter the name:", "Entry" + (i + 1) +

            JOptionPane.PLAIN_MESSAGE);

            

            phoneNumber = JOptionPane.showInputDialog(null,

            "Enter the phone number:", "Entry" + (i + 1) +

            JOptionPane.PLAIN_MESSAGE);

            

            //Secondary phonebook object (named it bookPhone)

            bookPhone.add(new PhoneBookEntry(name, phoneNumber));

            }

       //Create a loop that gets objects from the other class file and maybe switch them around

       System.out.println("Name"  + "\tPhone Number" );

       for (int i = 0; i < book.size(); i++)

            {


             System.out.println(book.get(i).getName() + "\t" + book.get(i).getPhoneNumber());

            }*/

    

    }


}



#2
lethalwire

lethalwire

    while(false){ ... }

  • Members
  • PipPipPipPipPipPipPip
  • 748 posts
  • Programming Language:Java, PHP
  • Learning:Java, PHP
There's a copy method defined in Collections (Java Platform SE 7 )
It's a static method that takes 2 List objects.
The first object is the destination array. The second object is the source array.

#3
AnnexTrunks

AnnexTrunks

    Newbie

  • Members
  • Pip
  • 5 posts
I'm afraid I do not know "enough" to understand what I see there. I am only in my 3rd month learning Java and it has been tough for me.

#4
lethalwire

lethalwire

    while(false){ ... }

  • Members
  • PipPipPipPipPipPipPip
  • 748 posts
  • Programming Language:Java, PHP
  • Learning:Java, PHP
What you're looking for on that link is:

Quote

static <T> void copy(List<? super T> dest, List<? extends T> src)

Static means you'll need to call the class name a (.)dot method name like this:
Collections.copy

Void means this method returns nothing. So you can't do something like
newArraylist = Collections.copy(...)
It's more like:
Collections.copy(...)

Now you'll notice the last part inside of the parentheses

Quote

(List<? super T> dest, List<? extends T> src)
This means this method takes 2 paramaters. Both parameters have to be of List type. You can ignore the <? and T> part as it is probably to advanced if you're 3 months in.

ArrayLists are of type List, so this method should work for you.


ArrayList<String> list1 = new ArrayList<String>();

ArrayList<String> list2 = new ArrayList<String>();


list1.add("a");

list1.add("b");

list1.add("c");


To copy:

Collections.copy(list2, list1); // copies list1 into list2. 



#5
AnnexTrunks

AnnexTrunks

    Newbie

  • Members
  • Pip
  • 5 posts
I thought when copying the array list, I only needed to make one list, and use something else to copy it? Like creating an object of it?

LOL, I am still having trouble.
    

ArrayList < PhoneBookEntry > book = new ArrayList < PhoneBookEntry > ();

 ArrayList<PhoneBookEntry> bookPhone = new ArrayList<PhoneBookEntry>();


book.add("a");

bookPhone.add("b");


To copy:

Collections.copy(book, bookPhone); // copies list1 into list2.



#6
lethalwire

lethalwire

    while(false){ ... }

  • Members
  • PipPipPipPipPipPipPip
  • 748 posts
  • Programming Language:Java, PHP
  • Learning:Java, PHP
It seems your post has been removed? Did you have any problems with the copy method?

#7
AnnexTrunks

AnnexTrunks

    Newbie

  • Members
  • Pip
  • 5 posts
Hmm, I'm not sure what happened. I've been tinkering with my code some more, and here is what I got.


import java.lang.reflect.Array;

import java.util.ArrayList;

import javax.swing.JOptionPane;

/* Exam Practice # 2

 * This file loads the array list with PhoneBookEntry objects, and displays the

 * content.

 */

public class PhoneBookDemo

{


    public static void main(String[] args)         <----------main method

    {   String name;

        String phoneNumber;

        String input;

        int inData;

        

        //Creates an array list that holds phonebookentrys, the name of it is called book

        ArrayList < PhoneBookEntry > book = new ArrayList < PhoneBookEntry > ();   <--------------my array list that refers to another class file I am using

       

        

        do//assure input is greater than 0

            {

            input = JOptionPane.showInputDialog("How many phone book listings to enter");

            inData = Integer.parseInt(input);

            }

        while(inData < 1);

        //load the array list

        for (int i = 0; i < inData; i++)

            {

            name = JOptionPane.showInputDialog(null,

            "Enter the name:", "Entry" + (i + 1) +

            JOptionPane.PLAIN_MESSAGE);

            

            phoneNumber = JOptionPane.showInputDialog(null,

            "Enter the phone number:", "Entry" + (i + 1) +

            JOptionPane.PLAIN_MESSAGE);

            

            //Primary phonebook object (named it book)

            book.add(new PhoneBookEntry(name, phoneNumber));

            

            }

       //Create a loop that gets objects from the other class file and maybe switch them around

       System.out.println("Name"  + "\tPhone Number" );

       for (int i = 0; i < book.size(); i++)

            {


             System.out.println(book.get(i).getName() + "\t" + book.get(i).getPhoneNumber());

            }

//*****************************Copied Object*******************************\\       <--------Here is where I made a "second empty" array. I get errors in netbeans though.

            //Copy of the primary object

             PhoneBookEntry[] copiedBook = ArrayList.copyOf(book, book.length);

            

             System.out.println("Name"  + "\tPhone Number" );

       for (int i = 0; i < copiedBook.size(); i++)

            {


             System.out.println(copiedBook.get(i).getName() + "\t" + copiedBook.get(i).getPhoneNumber());

            }


    }


}


My first array PhoneBookEntry works fine with my While loop, and if statement. Creating and copying my second arraylist is where I am having trouble. My understand is that, I create two array lists, I get info and fill one of them. The second one remains empty, until I want to copy and fill it in right? There should be some method for that I use, then I can create my while loop and if statement to display the contents of the second array. Is that all right?

#8
lethalwire

lethalwire

    while(false){ ... }

  • Members
  • PipPipPipPipPipPipPip
  • 748 posts
  • Programming Language:Java, PHP
  • Learning:Java, PHP
Are you wanting to copy an ArrayList<...> into a primitive array like PhoneBookEntry[]? Or into another ArrayList<PhoneBookEntry>?

If case 1, you'll need to use the toArray method from the ArrayList class.
If case 2, you'll need to use Collections.copy(...);




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users