티스토리 뷰

JAVA

Access ArrayList from another class

seoca 2019. 8. 1. 07:39

 

 

 

When ArrayList is needed from another class, use get/set method to return the list

다른 class에 있는 ArrayList를 사용하고 싶을 때는 get/set 메서드를 이용해서 불러오면 된다.

 

 

 

Example code I

 

class 1

import java.util.ArrayList;
import java.util.Iterator;
 
public class Main {
 
    public static void main(String[] args) {
        AnotherClass anotherClass = new AnotherClass();
 
        anotherClass.addList();
        ArrayList<Integer> list = anotherClass.getList();
 
        Iterator<Integer> itr = list.iterator();
 
        while (itr.hasNext()) {
            Integer i = itr.next();
            System.out.print(i + ", "); //1, 2, 3, 4,
        }
    }
}
 

 

class 2

import java.util.ArrayList;
 
public class AnotherClass {
 
    ArrayList<Integer> list = new ArrayList<>();
 
    public void addList() {
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
    }
 
    //setter
    public void setList(ArrayList list) {
        this.list = list;
    }
 
    //getter
    public ArrayList getList() {
        return list;
    }
}
 

 

 

*static으로 선언하고 사용할 수도 있지만 너무 심한 static method는 oop과 반대되기에 지양되어야 한다. 

 

 

 

 

 

 

Example code II

 

The code below reads a CSV file and prints ArrayList from another class 

CSV file 을 읽어서 ArrayList에 저장한 다음에 Main class에서 저장한 list를 출력하는 예제

 

//CSV File
Id,name,phone,email,account_num,address
1,Mr. D,345-234-2346,tomo@gmail.com,94837,Toronto CA
2,Mrs. P,847-835-3343,summer@gmail.com,98427,Vancouver CA
3,Mrs. C,938-656-6640,siw0911@yahoo.com,93247,Alberta CA
4,Mr. S,324-345-5531,suh@gmail.com,93442,Toronto CA
 
//Main class
public class Main {
 
    public static void main(String[] args) {
        CustomManager manager = CustomManager.createCustomManager();
 
        try {
            manager.readFile("customList.csv");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
 
        /////////////// 다른 class 에서 data 가지고 오기 //////////////////////
        ArrayList<CustomInfo> list = manager.getList();
        System.out.println(list.get(0)); //1,Mr. D,345-234-2346,tomo@gmail.com,94837,Toronto CA
    }
}
 
//Another Class
package customList;
 
import java.io.BufferedReader;
import java.io.*;
import java.util.ArrayList;
 
public class CustomManager {
    //ArrayList
    ArrayList<CustomInfo> customManagers = new ArrayList<>();
 
    //Singleton pattern
    static CustomManager inst = null;
    private CustomManager(){}
    public static CustomManager createCustomManager(){
        if(inst == null)
            inst = new CustomManager();
        return inst;
    }
 
    public void readFile(String csv) throws FileNotFoundException {
        BufferedReader csvFile = new BufferedReader(new FileReader("src" + File.separator + csv));
 
        try {
            String file = csvFile.readLine(); //to skip the first line
 
            while((file = csvFile.readLine()) != null){
                String[] data = file.split(",");
                //adding to ArrayList
                customManagers.add(new CustomInfo(Integer.parseInt(data[0]),data[1],data[2],data[3],data[4],data[5]));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
 
        for (CustomInfo c : customManagers) {
            System.out.println(c.toString());
        }
    }
 
    public ArrayList<CustomInfo> getList(){
       return customManagers;
    }
}
 

 

 

 

 

 

Reference

https://stackoverflow.com/questions/39989988/access-arraylist-from-another-class

'JAVA' 카테고리의 다른 글

Builder Pattern in Java  (0) 2019.08.09
Read CSV File and store data to MySQL  (0) 2019.08.01
The server time zone Error  (0) 2019.07.31
Connect to MySQL using Java JDBC  (0) 2019.07.31
Java is Pass-By-Value  (0) 2019.07.27