×
INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!
  • Students Click Here

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here

Jobs

How to use arraylist from one class into another class + add data in Java

How to use arraylist from one class into another class + add data in Java

How to use arraylist from one class into another class + add data in Java

(OP)
Hello everyone,

I am very new to Java

what I need to do is like below:

Public Class1
that is an arrayclass that holds multi arrays + lists is my thought.

Public Class2

here is where I fill the arrayclass from Class1 with arraydata.

Public Class3

here is where I use the array class1 that reiceved the data in class2


How do I make this?

basically passing arraylist with data to another class

Thank you in advance


Regards

RE: How to use arraylist from one class into another class + add data in Java

Hi Xsi,

It's not very complicated.

For example if you have a data-class (which contains data + getters and setters) - like this:

CODE

public class RecordSet {
  ...
} 

then you can create second class which has method for filling the data.
This method can return the data-class instance - like this:

CODE

public class RecordSetFill {
  public RecordSet fillInData() {
    RecordSet result = new RecordSet();
    ...
    return result;
  }
} 

then you can create third class which contains method for processing the data - e.g. printing the data.
This method could have the data-class instance as argument - for example:

CODE

public class RecordSetProcess {
  public void printRecordSet(RecordSet rs) {
    ...
    while (rs.next()) {
      ...
      System.out.printf(...);
      ...
    }
  }
} 

Then to test it all together create a fourth class which could look for example like this:

CODE

public class TestRecordSetProcessing {
  public static void main(String[] args) {
    // create instance of a class which populates RecordSet
    RecordSetFill recordSetFill = new RecordSetFill();
		
    // call method which returns instance of RecordSet
    RecordSet rs = recordSetFill.fillInData();
		
    // creates instance of a class which processes the recordSet  
    RecordSetProcess recordSetProcess = new RecordSetProcess();
		
    // call method which prints data contained in the RecordSet instance
    recordSetProcess.printRecordSet(rs);
  }
} 

If you would be interested in other implementation details I could post it here.

RE: How to use arraylist from one class into another class + add data in Java

(OP)
In my Case now I have got

CODE --> Java

import java.util.ArrayList;

public class Class1 {
	
	public  void MyArr() {
	
	 ArrayList<String> obj = new ArrayList<String>();
	 obj.add("MyTest1");
	 obj.add("MyTest2");
	 obj.add("MyTest3"); 
	 System.out.println("This is"+ obj);
	}
    
  
} 

then another class how do I add a new arrayelement here? (CLASS3 to the current ArrayList)

CODE --> Java

public class Class3 {
  public static void main(String[] args) {
	  
	  Class1 c1=new Class1();
	  
	  c1.MyArr();

  }
} 

how do I loop the array items I added in Class3 in Class4?

CODE --> Java

public class Class4 {
  public static void main(String[] args) {
	  
	  Class1 c1=new Class1();
	  
	  c1.MyArr();
  
  }
} 


Thank you in advance

RE: How to use arraylist from one class into another class + add data in Java

Hi Xsi,

IMO the best would be, when I post you my little working example, you take a look at it, try to understand it and then have questions. I didn't use naming like Class1, Class2, ...etc, because after a while I don't know what for is which class smile

#1. I created the data-class. It holds data in an ArrayList of Records.
1a) So first I created the class for one array element Record. It contains a data structure to hold my financial expenses (amount, date and a note which tells me what for I payed). Getters/setters were generated using the IDE (I have eclipse)
1b) Then I created the class RecordSet which contains an the ArrayList of Record and some methods to work with - which will be used later.

RecorSet.java

CODE

import java.util.ArrayList;

final class Record {
    private double amount;
    private int datum;
    private String note;

    public double getAmount() {
        return amount;
    }

    public void setAmount(double amount) {
        this.amount = amount;
    }

    public int getDatum() {
        return datum;
    }

    public void setDatum(int datum) {
        this.datum = datum;
    }

    public String getNote() {
        return note;
    }

    public void setNote(String note) {
        this.note = note;
    }
}

public class RecordSet {
    private ArrayList<Record> recSet = new ArrayList<Record>();
    private int recSetSize = 0;
    private int j = 0;
    // data from record on which the cursor position shows
    private Record currentRecord = new Record();

    public void add(double amount, int datum, String note) {
        Record rec = new Record();
        rec.setAmount(amount);
        rec.setDatum(datum);
        rec.setNote(note);
        this.recSet.add(rec);
    }

    private boolean hasNext() {
        this.recSetSize = recSet.size();
        return (j < this.recSetSize);
    }

    public boolean next() {
        boolean nextElementExist = hasNext();
        if (nextElementExist) {
            // fetch data in record
            this.currentRecord = this.recSet.get(j++);
        }
        return nextElementExist;
    }

    // Getters for getting data from currentRecord
    public double getAmount() {
        return currentRecord.getAmount();
    }

    public int getDatum() {
        return currentRecord.getDatum();
    }

    public String getNote() {
        return currentRecord.getNote();
    }
} 


#2. I wrote the class RecordSetFill which fills the data into the RecordSet object. It has only one method fillInData(). This method creates the instance of RecordSet, then adds three Records into RecordSet using the method RecordSet.add() and at end returns the RecordSet object filled with data.

RecordSetFill.java

CODE

public class RecordSetFill {
    public RecordSet fillInData() {
        RecordSet result = new RecordSet();
        int n = 0;
        System.out.println("Start filling records:");

        System.out.printf("    record #%02d\n", ++n);
        result.add(44.02, 20180409, "Payment at the gas station");

        System.out.printf("    record #%02d\n", ++n);
        result.add(7.90, 20180413, "10 Pilsner Beers");

        System.out.printf("    record #%02d\n", ++n);
        result.add(92.50, 20180414, "Saturday shopping with my wife");

        System.out.println("Done.\n");
        return result;
    }
} 


#3. Then I created the class RecordSetProcess which processes the RecordSet, i.e. it steps through all Records and prints them. For this purpose I have in the RecordSet the method next(). This method goes to the next Record (if possible) and fetch it's data into internal variable currentRecord. Then using the getters getAmount(), getDatum() and getNote() I will get the data out from data-object.

RecordSetProcess.java

CODE

public class RecordSetProcess {
    public void printRecordSet(RecordSet rs) {
        int n = 0;
        double amount;
        double total = 0;
        System.out.println("Now processing records:");
        while (rs.next()) {
            n++;
            amount = rs.getAmount();
            System.out.printf("#%02d: cost=%5.2f, date: %8d, what: %s\n", n,
                    amount, rs.getDatum(), rs.getNote());
            // total cost
            total += amount;
        }
        System.out.printf("%d records processed, total expenses = %6.2f \n", n,
                total);
    }
} 


#4. Finally to test all 3 classes together I created the class TestRecordSetProcessing. In the main() method it first creates the instance of RecordSetFill and calls it's method fillInData() which creates the instance RecordSet filled with data. Then it creates the instance of RecordSetProcess class and calls it's method printRecordSet, which takes as argument the instance of RecordSet and prints all records it contains.

TestRecordSetProcessing.java

CODE

public class TestRecordSetProcessing {
    public static void main(String[] args) {
        // create instance of a class which populates RecordSet
        RecordSetFill recordSetFill = new RecordSetFill();

        // call method which returns instance of RecordSet
        RecordSet rs = recordSetFill.fillInData();

        // creates instance of a class which processes the recordSet
        RecordSetProcess recordSetProcess = new RecordSetProcess();

        // call method which prints data contained in the RecordSet instance
        recordSetProcess.printRecordSet(rs);
    }
} 

When I run the test class I get this output:

CODE

Start filling records:
    record #01
    record #02
    record #03
Done.

Now processing records:
#01: cost=44.02, date: 20180409, what: Payment at the gas station
#02: cost= 7.90, date: 20180413, what: 10 Pilsner Beers
#03: cost=92.50, date: 20180414, what: Saturday shopping with my wife
3 records processed, total expenses = 144.42 

RE: How to use arraylist from one class into another class + add data in Java

Hi Xsi,

As I looked at your previous question about ArrayList, then maybe what I posted is too much as a first example on this topic. So better take it as second. Here is the modification simplified as possible - this should you try first:

#1. the data-class which holds only ArrayList of Strings:
StringList.java

CODE

import java.util.ArrayList;

public class StringList {
    public ArrayList<String> strings = new ArrayList<String>();
} 


#2. This class contains method which creates an instance of data-class, fills it with data and returns it:
StringListFill.java

CODE

public class StringListFill {
    public StringList fillData() {
        StringList result = new StringList();
        int n = 0;
        System.out.println("Start filling data:");

        result.strings.add("foo");
        System.out.printf("    record #%02d\n", ++n);
        result.strings.add("bar");
        System.out.printf("    record #%02d\n", ++n);
        result.strings.add("baz");
        System.out.printf("    record #%02d\n", ++n);
        result.strings.add("FooBar");
        System.out.printf("    record #%02d\n", ++n);
        result.strings.add("Spam");
        System.out.printf("    record #%02d\n", ++n);
        result.strings.add("Eggs");
        System.out.printf("    record #%02d\n", ++n);

        System.out.println("Done.\n");
        return result;
    }
} 


#3. This class contains method which takes the data-class as an argument and prints all its elements:
StringListProcess.java

CODE

public class StringListProcess {
    public void printStringList(StringList stringList) {
        int n = 0;
        System.out.println("Now processing List of Strings:");
        for (String string : stringList.strings) {
            n++;
            System.out.println(string);
        }
        System.out.printf("%d records processed.", n);
    }
} 


#4. Finally this is the test class:
TestStringList.java

CODE

public class TestStringList {
    public static void main(String[] args) {
        // create instance of a class which populates StringList
        StringListFill stringListFill = new StringListFill();

        // call method which returns instance of StringList
        StringList stringList = stringListFill.fillData();

        // creates instance of a class which processes the StringList
        StringListProcess stringListProcess = new StringListProcess();

        // call method which prints data contained in the StringList instance
        stringListProcess.printStringList(stringList);
    }
} 

Output:

CODE

Start filling data:
    record #01
    record #02
    record #03
    record #04
    record #05
    record #06
Done.

Now processing List of Strings:
foo
bar
baz
FooBar
Spam
Eggs
6 records processed. 

RE: How to use arraylist from one class into another class + add data in Java

(OP)
Thank you so much mikrom!

I am current is writing and translate your code. may take a hour lol :)

I am very sure I going to have questions to you later when I am done!

Thank you so much very grateful!

Best regards

Xsi

Red Flag This Post

Please let us know here why this post is inappropriate. Reasons such as off-topic, duplicates, flames, illegal, vulgar, or students posting their homework.

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members! Already a Member? Login

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close