Java Scanner Best Practice

限于喜欢 提交于 2019-12-13 19:16:39

问题


Question: I have a method that Instantiates a new Scanner Class with a BufferedReader, and returns the Scanner Class itself. As far as I understand it, Java will return the Scanner class - as a "copy" of the object (pass-by-value), as opposed to what we would call in C++ a Reference or Pointer. Provided that logic is correct - does that then mean, the Scanner instantiated in the method I call, will continue to stay OPEN and thus never be garbage collected?

For example: (bare bone)

private Scanner getDataFromWebService(String url)
{
    URLConnection sc = null;
    URL test = null;
    Scanner scanner = null;

    test = new URL(url);
    sc = test.openConnection();
    in = new BufferedReader(new InputStreamReader(sc.getInputStream());

    scanner = new Scanner(in);

    return scanner;
}

// Sample Call

Scanner newScanner = getDataFromWebService(url);

Secondly if you would be so kind to oblige; what happens then to the URLConnection and the BufferedReader, because if I close them before returning the Scanner in the getDataFromWebService Method - it will 'nullify' the returned Scanner. Perhaps the answer to this lies in the first question.

What would be best practice here, just never returning a complex object......


回答1:


You get a copy of the reference. So you'll still use the same object instance.



来源:https://stackoverflow.com/questions/12928616/java-scanner-best-practice

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!