从另一个类的一个类中获取数组中的值

时间:2012-05-24 14:26:36

标签: java arrays

我在一个类中有这个代码,并希望理想地将adjclose数组列表中的值复制到另一个类以进行进一步处理,同时保留原始数据。

我可以看到在填充数组时,在println语句之前使用return语句填充了arraylist。

然后main方法遍历arraylist再次显示arraylist adjclose中每个元素的值。

如何从另一个班级到达adjclose arraylist,以便我可以将它们复制到新的arraylist中进一步处理?

public ArrayList<Double> getadjClose(String symbol) {
    String baseUrl = "http://ichart.finance.yahoo.com/table.csv?ignore=.csv";
    baseUrl += "&s=" + symbol;
    baseUrl += "&a=" + startMonth;
    baseUrl += "&b=" + startDay;
    baseUrl += "&c=" + startYear;
    baseUrl += "&d=" + endMonth;
    baseUrl += "&e=" + endDay;
    baseUrl += "&f=" + endYear;
    baseUrl += "&g=" + freq;
    URL url;
    ArrayList<Double> adjclose = new ArrayList<Double>();
    System.out.print("Opening URL: ");
    System.out.print(baseUrl);
    System.out.println(" ");
    int counter = 0;
    try {
        url = new URL(baseUrl);
        BufferedReader in = new BufferedReader(new InputStreamReader(
                url.openStream()));
        in.readLine(); // Forward Header
        while (true) {
            String thisLine = in.readLine();
            if (thisLine == null) {
                break;
            }
            String[] separatedLine = thisLine.split("[,X]"); // split by commas
            adjclose.add(Double.parseDouble(separatedLine[6]));
            System.out.println(adjclose.get(counter) + " " + counter);
            counter = counter + 1;
        }
        return adjclose;
    } catch (IOException e) {
        return null;
    }
}

我现在对第一个类中的代码进行了更改,如下所示。

package yahooapi;

/**
 *
 * @author RSLOMA
 */
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;

public class YahooAPI {


int startMonth;
int startDay;
int startYear;

int endMonth;
int endDay;
int endYear;
int TodayDate;

String freq;

public ArrayList<Double> data = new ArrayList<>();


public ArrayList<Double>  getAdjClose(String symbol) throws IOException {
String baseUrl = "http://ichart.finance.yahoo.com/table.csv?ignore=.csv";
baseUrl += "&s=" + symbol;
baseUrl += "&a=" + startMonth;
baseUrl += "&b=" + startDay;
baseUrl += "&c=" + startYear;
baseUrl += "&d=" + endMonth;
baseUrl += "&e=" + endDay;
baseUrl += "&f=" + endYear;
baseUrl += "&g=" + freq;

URL url;

// use a local variable

ArrayList<Double> adjclose = new ArrayList<>(); 

System.out.print("Opening URL: ");
System.out.print(baseUrl);
System.out.println(" ");

int counter = 0;

try {
url = new URL(baseUrl);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));

in.readLine(); //Forward Header

while (true){
String thisLine = in.readLine();
if (thisLine == null){
break;
}
String[] separatedLine = thisLine.split("[,X]"); // split by commas

adjclose.add(Double.parseDouble(separatedLine[6]));
System.out.println(adjclose.get(counter) + " " + counter);

// update the data once the read is done

data = adjclose;
System.out.println(data.get(counter));

counter = counter + 1;

}


return adjclose;

} catch (IOException e) {
    return null;
}
}


public static void main(String args[]) throws IOException{
YahooAPI y = new YahooAPI();
Calendar cal = Calendar.getInstance();

y.startDay = 1;
y.startMonth = cal.get(Calendar.MONTH) - 1; //0 is jan, so 2 is march
y.startYear = cal.get(Calendar.YEAR) - 3;
System.out.println("Day: " + y.startMonth);
System.out.println("Day: " + y.startDay);
System.out.println("Day: " + y.startYear);

y.endDay = cal.get(Calendar.DATE) - (cal.get(Calendar.DATE) - 1);
y.endMonth = cal.get(Calendar.MONTH); //0 is jan, so 2 is march
y.endYear = cal.get(Calendar.YEAR);

y.freq = "m"; // d for daily frequency, w for weekly, m for monthly

ArrayList<Double> adjclose = y.getAdjClose("^GSPC");

//Iterator<Double> iter = adjclose.iterator();

//System.out.println("Returned Adjusted Close Values:");
//while (iter.hasNext()){
//System.out.println(iter.next());


int ArrayLngth = adjclose.size();

System.out.print("Array length = " + ArrayLngth + "    ");
}

    public ArrayList<Double> getAdjClose() {

        for (int counter = 0; counter<data.size(); counter++) {

            System.out.println(data.get(counter) + " " + counter);

    }



        return (ArrayList<Double>) data.clone();


    }



}

我想在另一个包中使用另一个类来进行计算,将原始数据元素保留在原始数组中,并将新计算的数据保存在第二个类的数组中。其他类的开头代码如下。如何调用以获取在data.clone()?

中克隆的数据
package PortfolioDesign;

/**
 *
 * @author RSLOMA
 */


public class MonthlyReturns {


        }

3 个答案:

答案 0 :(得分:1)

在第一个类中有一个方法可以创建数组的克隆并返回克隆,然后从第二个类中调用该方法。

答案 1 :(得分:1)

如果多次使用结果,我会将方法拆分为

  • 数据收集方法
  • 数据检索方法

数据收集器然后填充该类的成员:

private ArrayList<Double> data = new ArrayList<Double>();

public void  fillAdjClose(String symbol) throws IOException {
    String baseUrl = "http://ichart.finance.yahoo.com/table.csv?ignore=.csv";
    baseUrl += "&s=" + symbol;
    baseUrl += "&a=" + startMonth;
    baseUrl += "&b=" + startDay;
    baseUrl += "&c=" + startYear;
    baseUrl += "&d=" + endMonth;
    baseUrl += "&e=" + endDay;
    baseUrl += "&f=" + endYear;
    baseUrl += "&g=" + freq;
    URL url;

    // use a local variable
    ArrayList<Double> adjclose = new ArrayList<Double>();
    System.out.print("Opening URL: ");
    System.out.print(baseUrl);
    System.out.println(" ");
    int counter = 0;
    url = new URL(baseUrl);
    BufferedReader in = new BufferedReader(new InputStreamReader(
            url.openStream()));
    in.readLine(); // Forward Header
    while (true) {
        String thisLine = in.readLine();
        if (thisLine == null) {
            break;
        }
        String[] separatedLine = thisLine.split("[,X]"); // split by commas
        adjclose.add(Double.parseDouble(separatedLine[6]));
        System.out.println(adjclose.get(counter) + " " + counter);
        counter = counter + 1;
    }

    // update the date once the read is done
    data = adjclose;
}

public ArrayList<Double> getAdjClose() {
    return (ArrayList<Double>) data.clone();
}

您可以根据需要调用getAdjClose(),并始终获取上次读取数据的副本。

除非您还需要元素的副本,否则您始终可以将clone()用于ArrayList。由于您使用的是Double,这是不可变的,因此无需复制元素。

答案 2 :(得分:0)

如果您要将adjclose的值从Class A发布到Class B,那么包含的类ClassA理想情况下应该有一个可以称为my {的getter方法{1}}。

要保留原始数据,您应该发布ClassB的副本,而不是原始列表本身。另外需要注意的是,你应该做一个深度克隆而不是浅克隆。

adjClose

调用者类ClassB将创建一个ClassA实例并在其上调用getAdjClose()。

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public classA {
   private List<Double> adjclose = null;

   public List<Double> getAdjClose(){
     List<Double> returnValue = new ArrayList<Double>();
     if(adjclose != null) {
        returnValue.addAll(adjclose); // this will ensure that if caller makes any changes to adjClose, copy of classA remains intact.
        return returnValue;
     }
     return Collections.emptyList();
   }    
}